捕获返回按钮事件

如何检测用户在编辑 UITextField 时按下“返回”键盘按钮? 我需要这样做,以解除键盘时,用户按下“返回”按钮。

谢谢。

72761 次浏览
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}

Don't forget to set the delegate in storyboard...

enter image description here

Delegation is not required, here's a one-liner:

- (void)viewDidLoad {
[textField addTarget:textField
action:@selector(resignFirstResponder)
forControlEvents:UIControlEventEditingDidEndOnExit];
}

Sadly you can't directly do this in your Storyboard (you can't connect actions to the control that emits them in Storyboard), but you could do it via an intermediary action.

- (BOOL)textFieldShouldReturn:(UITextField *)txtField
{
[txtField resignFirstResponder];
return NO;
}

When enter button is clicked then this delegate method is called.you can capture return button from this delegate method.

SWIFT 3.0

override open func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(self, action: #selector(enterPressed), for: .editingDidEndOnExit)
}

in enterPressed() function put all behaviours you're after

func enterPressed(){
//do something with typed text if needed
textField.resignFirstResponder()
}

You can now do this is storyboard using the sent event 'Did End On Exit'.

In your view controller subclass:

 @IBAction func textFieldDidEndOnExit(textField: UITextField) {
textField.resignFirstResponder()
}

In your storyboard for the desired textfield:

enter image description here

Swift version using UITextFieldDelegate :

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
resignFirstResponder()
return false
}

Swift 5

textField.addTarget(textField, action: #selector(resignFirstResponder), for: .editingDidEndOnExit)