views:

236

answers:

1

Right, to begin my question, here's some screenies of the problem already solved by the Spotify app:

Spotify's Step 1: Standard UISearchBar not in editing mode.

Step 1

Spotify's Step 2: UISearchBar now in editing mode. Search term entered. Cancel button slides in from the right, and the clear button (grey x) appears.

Step 2

Spotify's Step 3: Cancel button pressed; keyboard slides out and the search bar is no longer in editing mode. Search term remains and the grey x button is now hidden.

Step 3

At present, the following code fires off when my cancel button is pressed:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

Which results in:

My Step 3: Search bar now not in editing mode. Cancel button and keyboard has slid out. Search term remains but so does the grey x.

Problem

So, my question is this: given that -resignFirstResponder (and -endEditing:, FYI) does not hide the grey x button when a search bar has had text entered into it, how does one hide it?

Thanks again, friends.

+1  A: 

The problem is that UISearchBar doesn't expose it's text field, and manages the properties on the text field itself. Sometimes, the values of the properties aren't what you want.

For instance, in my own app, I wanted the keyboard style for my search bar to use the transparent alert style.

My solution was to walk through the subviews of the search bar until you find the text field. You should then be able to set the clearButtonMode property, using something like UITextFieldViewModeWhileEditing as a parameter.

This should make it so that the clear button is only shown while the text field is editing.

You want to do this on viewDidLoad or something early, so it's set before you start using it (but after the search bar is initialised.

for (UIView *subview in searchBar.subviews)
{
    if ([subview conformsToProtocol:@protocol(UITextInputTraits)])
    {
        [(UITextField *)subview setClearButtonMode:UITextFieldViewModeWhileEditing];
    }
}
Jasarien
Cheers Jasarien, this seems to be exactly what I need. Unfortunately I'm running into an error with `[subview conformsToProtocol:UITextInputTraits]` which reads: `expected expression before 'UITextInputTraits'`. Do I need to import or conform to anything?
David Foster
My bad! Sorry. You need to do `[subview conformsToProtocol:@protocol(UITextInputTraits)]`
Jasarien
That's it! You're a genius. Thanks mate.
David Foster
BTW, did you use an app to make that little annotation on your screenshot, (argh! ->)? If so, what app? It looks useful :)
Jasarien
Unfortunately that was just a Photoshop brush tool jobbie. Though an annotation app is great idea!
David Foster