Swift version: 5.2
It’s common to have multiple gesture recognizers attached to a single view, all doing different things depending on the user’s taps on your screen. By default, iOS lets them fight for control, but usually you want to execute them in some sort of particular order: one gesture should only be matched if another failed.
For example, here are two gesture recognizers that exist on the same view:
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(executeSwipe)) let tap = UITapGestureRecognizer(target: self, action: #selector(executeTap)) view.addGestureRecognizer(swipe) view.addGestureRecognizer(tap)
A swipe gesture is a tap followed by a linear movement, whereas a tap is just a tap – we need to make sure the swipe gesture has definitely not been recognizer before the tap gesture is checked.
iOS often does a fairly good job of this, but there’s no need to leave it up to chance: if you call
require(toFail:) on the tap gesture recognizer, passing in the swipe recognizer, iOS will definitely make sure they don’t compete:
SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!
Available from iOS 3.2
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.