UITapGestureRecognizer
. The setup requires a few lines of code, but there is a way, you can handle background touches even more easy!What you need to do is just to change the root view type from
UIView
to UIControl
and attach an action. With Storyboard:
-
Select the root view.
-
In the Identity inspector simply change the type to
UIControl
. (Serious type change isn't required.)
-
Finally, connect an action to the Touch Down event using Connections inspector.
@IBAction func backgroundTouched(_ sender: Any) {
// Hide keyboard
view.endEditing(true)
}
If any child control interrupts a touch, it wouldn't be delivered to the background control! This is the main pro and con of this method. Sometimes it's exactly the desired behaviour to ignore touches on buttons. But other times you need to handle all the touches anywhere in the View Controller, like if you have a large UITextView and you want to hide the keyboard by tap.
No comments:
Post a Comment