UISearchBar within a UIToolbar won't show cancel button

ios, ipad, uisearchbar, uitoolbar

Solution

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];

Problem

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.

Original source