iOS 7 doesn't show cancel button of search bar in navigation bar

Codo picture Codo · Sep 28, 2013 · Viewed 18.4k times · Source

In an app that's supposed to run on iOS 6 and iOS 7, the cancel button of the search bar embedded in the navigation bar is not shown anymore if the app is run on iOS 7. On iOS 6, it works.

The search bar is in the title view of the navigation bar and the cancel button should be shown if the search bar becomes the first responder:

iOS 7

enter image description here

iOS 6

enter image description here

In an isolated test case, the code is very simple:

@interface MyViewController : UITableViewController<UISearchBarDelegate>

@property (nonatomic) IBOutlet UISearchBar* searchBar;

@end


@implementation MyViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView = self.searchBar;
}

- (void) searchBarTextDidBeginEditing: (UISearchBar*) searchBar {
    [searchBar setShowsCancelButton: YES animated: YES];
}

@end

Is this a deliberate change in iOS 7 that I missed in the documentation? If yes, what is supposed to be the alternative?

If not, have I made a mistake in my code?

Answer

Sam Spencer picture Sam Spencer · Sep 28, 2013

It looks like you're doing everything correctly, but apparently Apple has changed around some things in iOS 7. According to this SO question in iOS 7 the cancel button doesn't appear on a UISearchBar embedded in a UINavigationBar.

According to the developer documentation, the showsCancelButton property may have a slightly different effect than the setShowsCancelButton:Animated method. Try doing this:

searchBar.showsCancelButton = YES;
[searchBar setShowsCancelButton:YES animated:YES];

I'm not sure if that will have any impact. You could also try placing the code in a different delegate method:

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar; // return NO to not become first responder
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar; // called when text starts editing

You may also want to checkout the iOS 7 changelog. It looks like Apple changed the behavior or a UISearchDisplayController / UISearchBar when added to a UINavigationBar. Take a look at the last bullet point under the UIKit section (although it isn't clear exactly what was changed).


You may also want to try using a UISerachDisplayController. What might be even easier is to embed the UISearchBar in the header of a UITableView.