iPhone perform action when UITextField / UISearchBar's clear button is pressed

Dave picture Dave · Mar 8, 2010 · Viewed 13.5k times · Source

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

Answer

Kevin Sylvestre picture Kevin Sylvestre · Mar 8, 2010

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;
}