Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar within a UIToolbar won't show cancel button

I have a UISearchBar nested as a UIBarButtonItem within a UIToolbar. The basic functionality works, but the cancel button and the scope bar refuse to display. I've tried enabling them in the interface builder, and I've also tried manually calling [searchBar setShowsCancelButton:YES], but neither method works. Any ideas?

This is on an iPad. I tried in iOS 3, and it doesn't work in 4.2, either.

like image 508
Adam Crume Avatar asked Dec 07 '10 18:12

Adam Crume


2 Answers

You need to wrap the UISearchBar with another view.

UISearchBar *searchBar = [UISearchBar new];
UIView *searchBarContainer = [[UIView alloc] initWithFrame:searchBar.frame];
[searchBarContainer addSubview:searchBar];
UIBarButtonItem *searchBarItem =
    [[UIBarButtonItem alloc] initWithCustomView:searchBarContainer];
like image 94
sat.oh Avatar answered Nov 04 '22 10:11

sat.oh


You've simply hit a limitation on how UISearchBar works. One workaround is to layer the UISearchBar over the UIToolbar rather than having it genuinely live in the toolbar. This works visually because a search bar is painted just like a toolbar - their gradients are the same.

like image 27
matt Avatar answered Nov 04 '22 08:11

matt