🌚

Davis' Alt Notes

Swift Snippet: Dismiss Keyboard by Return

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

        exampleTextField.delegate = self
    }
}

extension SomeViewController: UITextFieldDelegate {
    // Dismiss Keyboard by Return
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    // Dismiss Keyboard by Tapping Other Areas
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}

, , , — Aug 21, 2020