为什么没有调用 textFieldShouldReturn 函数?

Why is the textFieldShouldReturn function not being called?

根本没有调用textFieldShouldReturn函数:没有错误,但键盘根本没有响应。

我的情况与 How to hide keyboard in swift on pressing return key? 不同,因为在我的情况下什么都没有发生,其他情况在 Objective-C。

这是我的代码:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

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

textField 是我故事板上文本字段的出口。我也试过 self.endEditing 而不是 resignFirstResponder.

这个答案的其余部分仍然非常有用,我会把它留在那里,因为它可能会帮助其他提问者...但是在这里,我错过了这个特定示例的明显问题...

我们不会在文本字段上调用 ​​resignFirstResponder。我们在视图控制器上调用它。我们需要在文本字段上调用它,因此将您的代码修改为如下所示:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

A UITextField 只会在作为其委托的对象上调用 textFieldShouldReturn 属性。

我们可以通过添加 viewDidLoad 方法来以编程方式解决此问题:

override func viewDidLoad() {
    super.viewDidLoad()
    self.textField.delegate = self
}

但我们也可以在构建时通过故事板进行设置。

右键单击文本框,查看是否已设置委托:

如果 delegate 旁边的圆圈未填充,则我们还没有为我们的 UITextField 设置委托。

要设置代表,请将鼠标悬停在此圆上。它将变为加号。现在单击并拖动到要委托文本字段的视图控制器(文本字段所属的视图控制器)。

当您适当地将视图控制器连接为委托时,此菜单应如下所示:

我注册了 Swift 4 Udemy 课程,讲师说除了 Cntrl 之外还要为 ViewController 添加 UITextFieldDelegate class - 从 textField 拖到ViewController 按钮并选择代表。

导入 UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

嗯,就我而言。我不小心启用了硬件键盘。确保取消选中 "Connect to hardware keyboard" 以便键盘显示在模拟器中。

硬件 -> 键盘 -> 连接到硬件键盘

希望这对其他人也有帮助!

如果使用 Swift 3+,您必须在第一个 属性 前添加下划线。喜欢:

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

这在 Apple 文档中也有很好的记录。 https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619603-textfieldshouldreturn

您可以在循环中设置所有文本字段委托:

var tF: [UITextField] = []

tf = [my1TextField, my2TextField, my3TextField]

for textField in tf {
    textField.delegate = self
}