用户在UITextField之外点击时关闭键盘

时间:2018-08-15 16:47:32

标签: ios scope uitextfield swift4 uitapgesturerecognizer

我有以下代码,当用户在文本字段之外点击时可以关闭键盘

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)

选择器功能如下:

@objc func dismissKeyboard() {
    view.endEditing(true)
}

代码的第一位在viewDidLoad中,这是我的问题。为什么在以下情况下不起作用: let tap UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))是在viewDidLoad()之外完成的?

1 个答案:

答案 0 :(得分:0)

self不能像您想要的那样被访问,您可以在VC内部的任何方法之外使用lazy var这样的

lazy var tap = { 
    return UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
}()