ios UITextField - 捕获返回按钮事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/976861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:00:41  来源:igfitidea点击:

UITextField - capture return button event

iosiphonecocoa-touchuitextfieldbackspace

提问by Ilya Suzdalnitski

How can I detect when a user pressed "return" keyboard button while editing UITextField? I need to do this in order to dismiss keyboard when user pressed the "return" button.

如何检测用户在编辑 UITextField 时按下“返回”键盘按钮的时间?我需要这样做才能在用户按下“返回”按钮时关闭键盘。

Thanks.

谢谢。

回答by Ilya Suzdalnitski

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


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

不要忘记在故事板中设置委托...

enter image description here

在此处输入图片说明

回答by mxcl

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.

遗憾的是,您无法在 Storyboard 中直接执行此操作(您无法将操作连接到在 Storyboard 中发出它们的控件),但您可以通过中间操作来执行此操作。

回答by drpawelo

SWIFT 3.0

斯威夫特 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

在 enterPressed() 函数中放置您所追求的所有行为

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

回答by Blake Lockley

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

在此处输入图片说明

回答by Leo Dabus

Swift version using UITextFieldDelegate :

使用 UITextFieldDelegate 的 Swift 版本:

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

回答by Ted

Swift 5

斯威夫特 5

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

回答by Mahendra Vishwakarma

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

单击输入按钮时,将调用此委托方法。您可以从此委托方法捕获返回按钮。