如何让所有文本字段在 return 上关闭键盘?

How to make all textfields close keyboard on return?

我目前正在学习 Swift 并且我的应用程序中有一些 TextFields。现在我希望用户在 TextField 中按下 return 键或点击屏幕上的任意位置时关闭键盘。

目前我在所有我不太喜欢的控制器中添加了相同的代码。有没有办法让所有控制器/TextFields 都按照我上面描述的方式运行。

关闭键盘 return:

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

点击屏幕关闭键盘:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

我想在我所有的控制器中都有这个,而不是每次都复制它。

您可以子class UITextField 并创建您自己的 TextField。如果您将 UITextField 添加到 Storyboard,只需在身份检查器中将 class 设置为您的文本字段 class。

class YourTextField : UITextField, UITextFieldDelegate {
    override init(){
        super.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.delegate = self
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.delegate = self
    }

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