【问题标题】:Dismiss keyboard through return key with swift快速通过返回键关闭键盘
【发布时间】:2015-10-19 17:45:06
【问题描述】:

我是一名使用 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”方法中使用它时,它工作正常。你能告诉我我在我的代码中犯了什么错误吗?谢谢。

【问题讨论】:

  • 你设置了 UITextField 的代理了吗?
  • 您没有覆盖 textField... 函数。我敢打赌那是你的问题。
  • 是的。那是我做错了。谢谢大家

标签: ios swift keyboard xcode6 dismiss


【解决方案1】:

尝试设置委托。将 didSet 添加到文本出口。像这样。

    @IBOutlet var text: UITextField! {
      didSet {
       text.delegate = self
      }
}

【讨论】:

    【解决方案2】:

    resignFirstResponder() 方法是正确的。通过在textFieldShouldReturn() 方法中使用textField.resignFirstResponder(),它适用于每个文本字段。

    就是这样:

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

    【讨论】:

    • 这就是我所拥有的。仅当您将委托添加到文本字段时才有效。
    猜你喜欢
    • 2015-01-15
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 2021-06-29
    • 2016-08-25
    相关资源
    最近更新 更多