如何添加对 UITextField 返回键的操作?

在我的视图中有一个按钮和文本字段。当我点击文本字段时,键盘就会出现,我可以在文本字段上写字,我也可以通过点击按钮解除键盘,添加:

[self.inputText resignFirstResponder];

现在我要启用键盘的返回键。当我将按键盘上的键盘会消失,有些事情会发生。我怎么能这么做?

95732 次浏览

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

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

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)

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()
}