简体   繁体   English

如何在 UITextField 返回键上添加操作?

[英]how to add an action on UITextField return key?

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?我怎样才能做到这一点?

Ensure "self" subscribes to UITextFieldDelegate and initialise inputText with:确保“self”订阅UITextFieldDelegate并使用以下命令初始化 inputText:

self.inputText.delegate = self;

Add the following method to "self":将以下方法添加到“self”:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.inputText) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

Or in Swift:或者在 Swift 中:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if textField == inputText {
        textField.resignFirstResponder()
        return false
    }
    return true
}

With extension style in swift 3.0 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然后在视图控制器的扩展中符合UITextFieldDelegate

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在 viewDidLoad() 中,添加

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 or viewDidLoad;只需在 textField 设置函数或 viewDidLoad 上添加一个目标; then add its related objective C func as selector.然后将其相关的目标 C 函数添加为选择器。

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

当点击键盘完成按钮时,对从 UITextField 发送的“primaryActionTriggered”UIEvent 使用 Target-Action UIKit 机制。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM