Combine gestures to create complex interactions.
When you add multiple gestures to your app’s view hierarchy, you need to decide how the gestures interact with each other. You use gesture composition to define the order SwiftUI recognizes gestures. There are three gesture composition types:
When you combine gesture modifiers simultaneously, SwiftUI must recognize all subgesture patterns at the same time for it to recognize the combining gesture. When you sequence gesture modifiers one after the other, SwiftUI must recognize each subgesture in order. Finally, when you combine gestures exclusively, SwiftUI recognizes the entire gesture pattern when SwiftUI only recognizes one subgesture but not the others.
Sequence One Gesture After Another
When you sequence one gesture after another, SwiftUI recognizes the first gesture before it recognizes the second. For example, to require a long press before the user can drag a view, you sequence a
Drag after a
Model Sequenced Gesture States
To make it easier to track complicated states, use an enumeration that captures all of the states you need to configure your views. In the following example, there are three important states: no interaction (
inactive), long press in progress (
pressing), and dragging (
Create Gestures and Update the UI State
When you sequence two gestures, the callbacks capture the state of both gestures. In the update callback, the new
value uses an enumeration to represent the combination of the possible gesture states. The code below converts the underlying gesture states into the high-level
Drag enumeration defined above.
When the user begins pressing the view, the drag state changes to
pressing and a shadow animates under the shape. After the user finishes the long press and the drag state changes to
dragging, a border appears around the shape to indicate that the user may begin moving the view.