Call textFieldDidEndEditing of UITextField when press UIButton

3.1k Views Asked by At

Is there anyway to call textFieldDidEndEditing of UITextField when pressed UIButton?

Current process is function in textFieldDidEndEditing can work when user press "Return" or "Done" button and click on UIButton. To make it clear, if ABC function in textFieldDidEndEditing to be run, user must press "Return" or "Done" button of Keyboard and then click on UIButton.

What I want is I want to run function in textFieldDidEndEditing can work when user press UIButton.

2

There are 2 best solutions below

7
On BEST ANSWER

In the button handler method, call:

[self.view endEditing:YES];

This will force the keyboard to disappear and whatever the current text field had the focus will resign first responder and the textFieldDidEndEditing: method will be called for it.

The above assumes the button handler is in the view controller class.

Since you are dealing with a custom cell and the button is in the custom cell, simply do:

[self endEditing:YES];

where self is the custom cell. This will resign any text field in the cell.

2
On

You can use textfield UIKeyboardWillHideNotification Notification

- (void)viewDidLoad 
{
     [super viewDidLoad];
        // register for keyboard dismiss notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)  name:UIKeyboardWillHideNotification object:nil];
}
 - (void)keyboardWillHide:(NSNotification *)notification
{
     // This function will be called whenever the keyboard hides. So you can implement your textFieldDidEndEditing code here.
}

Also when your button is clicked just resign the textfield by

[yourTextField resignFirstResponder];