问题描述
我是使用Swift的初学者程序员.我一直在做一个待办事项清单应用程序.我试图通过回车键关闭键盘.我已经尝试过'self.view.endEditing(true)'和'resignFirstResponder()'方法,但是它们都不起作用.这是我的代码:(我正在使用标签应用程序)
I am a beginner programmer working with Swift. I have been working on a to-do list application. I am trying to dismiss a keyboard through the return key. I have tried the 'self.view.endEditing(true)' and the 'resignFirstResponder()' methods, but neither of them are working. Here is my code: (I am using a tab-application)
class SecondViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var text: UITextField!
@IBAction func addItem(sender: AnyObject) {
toDoList.append(text.text)
text.text = ""
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true) // This works fine here
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true) // This is not working...
return true
}
}
在最后一个功能中,我还尝试使用以下命令:
At the last function, I have also tried using the following:
func textFieldShouldReturn(textField: UITextField) -> Bool {
text.resignFirstResponder() // This is not working...
return true
}
但是由于某种原因,没人能按照我的意愿工作.当我在'touchesBegan'方法中使用它时,它可以正常工作.您能告诉我我的代码有什么错误吗?谢谢.
But for some reason, neither one is working as I want it to. When I use it in the 'touchesBegan' method, it works fine. Could you please show me what error I am making in my code? Thanks.
推荐答案
尝试设置委托.将didSet添加到文本出口.这样.
Try setting the delegate. Add a didSet to the text outlet. Like this.
@IBOutlet var text: UITextField! {
didSet {
text.delegate = self
}
}
这篇关于快速通过回车键关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!