我是一名使用 Swift 的初级程序员。我一直在开发待办事项列表应用程序。我试图通过返回键关闭键盘。我已经尝试过“self.view.endEditing(true)”和“resignFirstResponder()”方法,但它们都不起作用。这是我的代码:(我正在使用标签应用程序)
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
}
}
在最后一个函数中,我还尝试使用以下方法:
func textFieldShouldReturn(textField: UITextField) -> Bool {
text.resignFirstResponder() // This is not working...
return true
}
但出于某种原因,没有一个能按我希望的那样工作。当我在“touchesBegan”方法中使用它时,它工作正常。你能告诉我我在代码中犯了什么错误吗?谢谢。
最佳答案
尝试设置委托(delegate)。将 didSet 添加到文本导出。像这样。
@IBOutlet var text: UITextField! {
didSet {
text.delegate = self
}
}
关于ios - 通过快速返回键关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688686/