如何在返回键被击中时隐藏键盘 - 斯威夫特 [英] How to hide keyboard when return key is hit - Swift
本文介绍了如何在返回键被击中时隐藏键盘 - 斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在点击返回键时隐藏iOS键盘,但是它会停止并给出图像中看到的错误。这是我正在使用的代码:
Trying to hide the iOS keyboard when the return key is hit, but instead it halts and gives me the error seen in the image. Here's the code I'm using:
@IBOutlet weak var scoreText: UITextField!
func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
推荐答案
您的问题是您没有委托textField以便使用该方法。首先,您的类必须包含 UITextFieldDelegate
协议:
Your problem is that you didn't delegate a textField in order to use that method. First, your class must include the UITextFieldDelegate
protocol:
class yourClass: UIViewController, UITextFieldDelegate { ... }
并且在 viewDidLoad()
方法,也可以添加:
And in the viewDidLoad()
method, add this as well:
scoreText.delegate = self
然后你必须改变这个:
func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
到此:
func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
最终代码:
class yourClass: UIViewController, UITextFieldDelegate {
@IBOutlet weak var scoreText: UITextField!
override func viewDidLoad(){
super.viewDidLoad()
scoreText.delegate = self
}
func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
self.view.endEditing()
return true
}
}
如果这不起作用,则问题不在于 textFieldShouldReturn()
函数。请检查您的插座连接。
If this is not working, the problem is not the textFieldShouldReturn()
function. Please check your outlet connections.
这篇关于如何在返回键被击中时隐藏键盘 - 斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文