how to add an action on UITextField return key?
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...
}
Ensure "self" subscribes to UITextFieldDelegate
and initialise inputText with:
self.inputText.delegate = self;
Add the following method to "self":
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == self.inputText) {
[textField resignFirstResponder];
return NO;
}
return YES;
}
Or in Swift:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == inputText {
textField.resignFirstResponder()
return false
}
return true
}
With extension style in swift 3.0
First, set up delegate for your text field.
override func viewDidLoad() {
super.viewDidLoad()
self.inputText.delegate = self
}
Then conform to UITextFieldDelegate
in your view controller's extension
extension YourViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == inputText {
textField.resignFirstResponder()
return false
}
return true
}
}