Saturday, June 30, 2018

Handling background touches: UIControl instead of UITapGestureRecognizer

Usually, to handle background touches on a View Controller we add a 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:
  1. Select the root view.
  2. In the Identity inspector simply change the type to UIControl. (Serious type change isn't required.)
  3. Finally, connect an action to the Touch Down event using Connections inspector.
Then the action can be utilized, for example, to hide a keyboard: @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

How to Record Calls on iPhone