Search This Blog

Monday, February 27, 2017

3 ways to hide keyboard in ios

There is one of most popular issues in ios development. How to hide keyboard on touch outside or when Return button is tapped in keyboard. There are different ways how to do it.


1. override func touchesBegan


The easiest one. Just override one method of UIView - touchesBegan and invoke method endEditing of view.

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
   
}

2. Using UITapGestureRecognizer


Create gesture recognizer for tap gestures and add it to the view. On gesture handler hide the keyboard.

class ViewController: UIViewController {
    
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let tapRecognizer = UITapGestureRecognizer(target: self, 
            action: #selector(ViewController.dismissKeyboard))
        self.view.addGestureRecognizer(tapRecognizer)
    }
    
    func dismissKeyboard() {
        self.textField.resignFirstResponder()
    }
    
}

3. Using UITextFieldDelegate

There is how to hide keyboard when Return button of Keyboard is tapped. We need to be UITextFieldDelegate, make self as delegate and implement textFieldShouldReturn method in which we will hide keyboard.

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.textField.delegate = self
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.dismissKeyboard()
        return false
    }
   
}