19

Is it possible to gain access to a delegate method that will allow additional actions to be performed when the "clear" button is pressed on a UITextField / UISearchBar?

Thanks

Dave
  • 363
  • 2
  • 3
  • 9
  • check out the answer here http://stackoverflow.com/questions/1092246/uisearchbar-clearbutton-forces-the-keyboard-to-appear – Hiren May 16 '12 at 11:37

5 Answers5

35

See: UITextFieldDelegate Protocol Reference

If you set your view controller as the delegate for your text field (can be done in interface builder), you can use:

- (void)clearSearchTextField
{
  ...
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
  if (textField == self.searchTextField) [self clearSearchTextField];
  return YES;
}
Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
7

For Swift 3:

To perform an action when the "clear" button is pressed on a UITextField

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    if textField == yourTextFieldName {
        // do some action
    }
    return true
}
Rbar
  • 3,740
  • 9
  • 39
  • 69
1

For a UISearchBar you will want to implement func searchBar(searchBar: UISearchBar, textDidChange searchText: String).

This is triggered before func searchBarTextDidBeginEditing(searchBar: UISearchBar) and before func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool as well.

You implementation should look something like this:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText == "" {
            //Code to execute when search is cleared
        }
    }
Barlow Tucker
  • 6,229
  • 3
  • 36
  • 42
0

When you clear the text field several events will happen that you will have access to through either the UISearchDisplayDelegate or the UISearchBarDelegate such as searchBar:textDidChange and searchDisplayController:shouldReloadTableForSearchString

This will also cause the search table to hide so it will trigger

searchDisplayController:willHideSearchResultsTableView  
searchDisplayController:didHideSearchResultsTableView

When the search table will hide you can check if the search text is empty and then do whatever you need to do.

Hiren
  • 12,720
  • 7
  • 52
  • 72
GhostM
  • 408
  • 3
  • 7
-1

See my answer here: https://stackoverflow.com/a/3852509/91458 – it’s for a searchBar but should apply to a textField as well.

Community
  • 1
  • 1
boliva
  • 5,604
  • 6
  • 37
  • 39