尝试在点击返回键时隐藏iOS键盘,但是它会停止并给出图像中看到的错误。以下是我使用的代码:
@IBOutlet weak var scoreText: UITextField!
func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
答案 0 :(得分:25)
您的问题是您没有委派textField来使用该方法。首先,您的班级必须包含UITextFieldDelegate
协议:
class yourClass: UIViewController, UITextFieldDelegate { ... }
在viewDidLoad()
方法中,也可以添加:
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()
功能。请检查您的插座连接。
答案 1 :(得分:2)
试试这个
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
答案 2 :(得分:1)
在快速4或5中,您可以像这样使用:
这里是完整代码
class ViewController: UIViewController,UITextFieldDelegate {
//Connect to text field
@IBOutlet weak var scoreText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//must initialize delegate
scoreText.delegate = self
}
//add method
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}