Composing Gestures
Combine gestures using .simultaneousGesture or .highPriorityGesture and coordinate interactions.
Syntax
Compose: Add .simultaneousGesture() to run together, or .highPriorityGesture() to give precedence to one gesture.
Simultaneous Tap + Drag
Both gestures run: taps increment a counter while dragging changes color.
Example
Demo.swift
ContentView.swift
App.swift
import SwiftUI
struct ComposeSimultaneousDemo: View {
@State private var tapped = 0
@State private var dragged = false
var body: some View {
Rectangle()
.fill(dragged ? .orange : .purple)
.frame(height: 120)
.overlay(Text("taps: \(tapped)"))
.simultaneousGesture(TapGesture().onEnded { tapped += 1 })
.gesture(DragGesture().onChanged { _ in dragged = true }.onEnded { _ in dragged = false })
}
}
In the example above, both the tap and drag gestures run.
High Priority Drag Over Tap
Drag takes precedence over tap: while dragging, taps do not increment the counter.
Example
Demo.swift
ContentView.swift
App.swift
import SwiftUI
struct ComposePriorityDemo: View {
@State private var tapped = 0
@State private var dragging = false
var body: some View {
Rectangle()
.fill(dragging ? .orange : .purple)
.frame(height: 120)
.overlay(Text("taps: \(tapped)"))
.highPriorityGesture(DragGesture().onChanged { _ in dragging = true }.onEnded { _ in dragging = false })
.gesture(TapGesture().onEnded { if !dragging { tapped += 1 } })
}
}
Leave a Reply