Magnus
Magnus

Reputation: 1442

Reset text in textfield of UISearchBar when X button is clicked, but not resign firstresponder

I have a view with a UISearchBar in it. However, when the "X" button in the searchbar is clicked, it removes the keyboard but doesn't remove the text in the textfield of the searchbar. What I want is this: When the user clicks the x button, the text in the textfield is reset but the keyboard stays up.

How can I do this?

Upvotes: 8

Views: 13391

Answers (4)

Mouhamad Lamaa
Mouhamad Lamaa

Reputation: 884

to clear text use this searchBar.text = @"";

Upvotes: 0

Harald
Harald

Reputation: 432

Just set the text to nil in searchBarCancelButtonClicked delegate method :

searchBar.text = nil;

Upvotes: 7

flizit
flizit

Reputation: 389

This seems to do the trick for me. Make sure your View Controller is a UISearchBarDelegate

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
}

Upvotes: 10

Nick
Nick

Reputation: 2646

try implementing UISearchBarDelegate's method -(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar and return NO as the result.

E.g.:

    - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
    {
        return NO;
    }

Upvotes: -1

Related Questions