Search code examples
iosscopeuitextfieldswift4uitapgesturerecognizer

Dismissing keyboard when user taps outside of UITextField


I have the following code for dismissing the keyboard when a user taps outside of the text field

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

The selector function is the following:

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

The first bit of code is in the viewDidLoad, which is what my question is about. Why doesn't it work if: let tap UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) is done outside of the viewDidLoad() ?


Solution

  • self can't be accessed like what you want it to , you can use a lazy var like this outside of any method inside the VC

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