iDev: UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

While working on a particular UISearchBar I ran into 2 little problems, both easy to fix but I thought of posting them in case someone is stuck. What I needed was to make the cancel button and the scope bar to be displayed only while editing. I believe that this should be a pretty common thing to do, and the first part is pretty straight forward:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = YES;

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = NO;

return YES:

}

That is pretty simple, specially if you don’t forget to associate the UISearchBar’s delegate!

Next, I tried the same with the scope bar but it didn’t work – the scope bar wouldn’t appear. During my testing, I tried to start with the scope bar displayed and then hiding it after the first edit… it worked but when disappearing the search bar would preserve the height as if it was still showing the scope bar!

The final solution is a simple call to [searchBar sizeToFit] and everything works as smooth as it should. Here is the complete code with the small bonus of animating the cancel button’s (dis)appearance:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = YES;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:YES animated:YES];

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = NO;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:NO animated:YES];

return YES;

}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s