I add UISearchBar above UINavigationBar and set UIsearchbar showsCancelButton YES, work fine in iOS6 but in iOS7 not showing cancel button. I used below code snippet
I had similar problem, on iPhone search bar with cancel button show well, but on iPad the cancel button wasn't shown. Wrapping the UIsearchBar to UIView like @Rodskjegg throw style issue. On iPad UIsearchBar setting it as the titleView of a navigationItem and add UIBarButtonItem to setRighttBarButtonItem as UIBarButtonSystemItemCancel.
[self.navigationItem setLeftBarButtonItem:Nil animated:YES];
self.navigationItem.titleView = self.searchBar;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(searchBarCancelButtonClicked:)];
[self.navigationItem setRightBarButtonItem: cancelButton animated:YES];
}
else {
[self.navigationItem setRightBarButtonItem: nil animated:YES];
}
Yes In iOS 7 button is located on the screen, but it's title could be invisible My solution was to set Search Style to "Minimal" and choose bar tint colour for "Cancel" text colour in IB
And the Result in a simulator :
Implement the search bar delegate and use this:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton = YES;
}
I had the same problem, on iPhone the search cancel was shown well, but on iPad it didn't.
The workaround of wrapping the UISearchBar in another UIView didn't work well for me since it had different appearance and wrong width on rotation.
My solution is a simple one - use search WITHOUT cancel, and add cancel as UIBarButtonItem.
Since iOS 7 you can just set the property displaysSearchBarInNavigationBar
to YES
on the UISearchDisplayController
to automatically get a UISearchbar
in the NavigationBar.
I ran into the same problem, here's my solution, hope this helps.
Some further explanation:
I found out that sending setShowsCancelButton:animated:
to the searchBar, it just works like magic. And the cleanest way to add a searchBar to navigation bar is self.navigationItem.titleView = self.searchBar;
The appropriate timing for calling setShowsCancelButton:animated:
is in searchBarTextDidBeginEditing:
and searchBarTextDidEndEditing:
delegate methods, so remember to set self
to be the delegate of searchBar.
- (void)viewDidLoad
{
self.navigationItem.titleView = self.searchBar;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
}