If you want to dismiss the keyboard when you touch anywhere outside a text field, choose one of these ways:
Dismiss keyboard in a view with no scrollview/tableview
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) }(Note: This will not work on a scrollview or tableview.)
Dismiss keyboard when touching inside a scrollview/tableview
- Add a TapGestureRecognizer to your storyboard's scene
- Create an action outlet in your viewcontroller with the code below
@IBAction func TapGestureRecognizer_Action(_ sender: UITapGestureRecognizer) { view.endEditing(true) }
All in code
override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.endEditing)) view.addGestureRecognizer(tapGesture) } func endEditing() { view.endEditing(true) }(Xcode 8, Swift 3.0)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.