UISearchBar within a UIToolbar won't show cancel button
Asked Answered
U

3

5

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.

Underground answered 7/12, 2010 at 18:1 Comment(0)
U
11

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];
Underfoot answered 9/1, 2011 at 15:13 Comment(0)
T
3

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.

Tonality answered 29/12, 2010 at 22:52 Comment(0)
D
0

is it really necessary to ever use a Cancel button in a search bar? Just use the textDidChange method to see if the string has been cleared and use that to do the same thing the cancel would.

Dunlap answered 19/9, 2012 at 15:58 Comment(1)
so you're saying that whenever the user deletes the last character the keyboard should dismiss and editing end? That seems like presumptuous behavior on the part of the app.Medawar

© 2022 - 2024 — McMap. All rights reserved.