gpt4 book ai didi

swift - 为什么没有调用 textFieldShouldReturn 函数?

转载 作者:IT王子 更新时间:2023-10-29 05:24:54 26 4
gpt4 key购买 nike

根本没有调用 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 是我 Storyboard上文本字段的导出。我还尝试了 self.endEditing 而不是 resignFirstResponder

最佳答案

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

我们没有在文本字段上调用 ​​resignFirstResponder。我们在 View Controller 上调用它。我们需要在文本字段上调用它,因此将您的代码修改为如下所示:

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

UITextField 只会调用作为其委托(delegate)的对象的 textFieldShouldReturn 属性。

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

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

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

右键单击文本框,查看是否设置了委托(delegate):

enter image description here

如果 delegate 旁边的那个圆圈是空的,我们还没有为我们的 UITextField 设置委托(delegate)。

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

enter image description here

当您适本地将 View Controller 连接为委托(delegate)时,此菜单应如下所示:

enter image description here

关于swift - 为什么没有调用 textFieldShouldReturn 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com