Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 398
Dave Avatar asked Mar 08 '10 21:03

Dave


People also ask

What is uisearchbar in UiPath?

UISearchBar provides a text field for entering text, a search button, a bookmark button, and a cancel button. A search bar doesn’t actually perform any searches. You use a delegate, an object conforming to the UISearchBarDelegate protocol, to implement the actions when the user enters text or clicks buttons.

How do I clear text in a text field programatically?

The behavior of the clear button. The clear button is a built-in overlay view that the user taps to delete all of the text in a text field. Use this attribute to define when the clear button appears. To set this attribute programatically, use the clearButtonMode property. The minimum font size for the text field’s text.

How to hide the text in a text field programmatically?

When the text field’s string is empty, the text field displays this string instead, formatting the string so as to indicate that it is not the actual text. Typing any text into the text field hides this string. To set this attribute programmatically, use the placeholder property. The background image to display when the text field is enabled.

How does the appearance and dismissal of the keyboard affect text fields?

The appearance and dismissal of the keyboard affect the editing state of the text field. When the keyboard appears, the text field enters the editing state and sends the appropriate notifications to its delegate. Similarly, when the text field resigns the first responder status, it leaves the editing state and notifies its delegate.


2 Answers

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;
}
like image 60
Kevin Sylvestre Avatar answered Oct 02 '22 09:10

Kevin Sylvestre


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
}
like image 36
Rbar Avatar answered Oct 02 '22 08:10

Rbar