Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove clear button (grey x) to the right of UISearchBar when cancel button tapped

Tags:

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.

like image 833
David Foster Avatar asked Jun 16 '10 10:06

David Foster


1 Answers

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];     } } 
like image 92
Jasarien Avatar answered Oct 13 '22 23:10

Jasarien