how to add an action on UITextField return key?

Viewed 95363

I have a button and text textfield in my view. when i click on the textfield a keyboard appears and i can write on the textfield and i also able to dismiss the keyboard by clicking on the button by adding:

[self.inputText resignFirstResponder];

Now I want to enable return key of keyboard. when i will press on the keyboard keyboard will disappear and something will happen. How can I do this?

5 Answers

While the other answers work correctly, I prefer doing the following:

In viewDidLoad(), add

self.textField.addTarget(self, action: #selector(onReturn), for: UIControl.Event.editingDidEndOnExit)

and define the function

@IBAction func onReturn() {
    self.textField.resignFirstResponder()
    // do whatever you want...
}

Just add a target on textField setup function on viewDidLoad, then add its related function as selector.

override func viewDidLoad() {
    super.viewDidLoad() 
    textField.addTarget(self, action: #selector(textFieldShouldReturn(sender:)), for: .primaryActionTriggered)
}

@objc func textFieldShouldReturn(sender: UITextField) {
    textField.resignFirstResponder()
}

Use Target-Action UIKit mechanism for "primaryActionTriggered" UIEvent sent from UITextField when a keyboard done button is tapped.

textField.addTarget(self, action: Selector("actionMethodName"), for: .primaryActionTriggered)
Related