
Swiftui Gestures
- 2.7k installs
- 944 repo stars
- Updated July 15, 2026
- dpearson2699/swift-ios-skills
swiftui-gestures implements SwiftUI tap, drag, magnify, rotate, and composed gestures with conflict resolution for iOS 26+.
About
The swiftui-gestures skill implements and reviews SwiftUI gesture handling for iOS 26 plus using Swift 6.3 patterns. It covers discrete gestures TapGesture and LongPressGesture and continuous DragGesture, MagnifyGesture, and RotateGesture with composition via simultaneously, sequenced, and exclusively modifiers. GestureState with updating provides transient press feedback without polluting view state. View attachment uses gesture, highPriorityGesture, and simultaneousGesture for parent-child conflict resolution. Custom Gesture protocol conformances are documented alongside migration from deprecated MagnificationGesture to MagnifyGesture. Scope excludes broad SwiftUI architecture owned by swiftui-patterns and UIKit bridging owned by swiftui-uikit-interop. A review checklist and common mistakes section guide corrections with Apple documentation citations when fixing API availability claims for SpatialTapGesture, rotate gesture value handling, velocity-based drag end predictions, and accessibility alternatives for gesture-driven tap, long press, drag, and pinch interactions on iOS.
- Tap, long press, drag, magnify, and rotate gesture patterns for iOS 26+.
- Compose gestures with simultaneously, sequenced, and exclusively.
- GestureState updating for transient press and drag feedback.
- Resolve conflicts with highPriorityGesture and simultaneousGesture.
- Migrate MagnificationGesture to MagnifyGesture on iOS 17+.
Swiftui Gestures by the numbers
- 2,744 all-time installs (skills.sh)
- +125 installs in the week ending Jul 29, 2026 (Skillselion tracking)
- Ranked #66 of 1,039 Mobile Development skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 31, 2026 (Skillselion catalog sync)
swiftui-gestures capabilities & compatibility
- Capabilities
- discrete and continuous built in gesture pattern · gesture composition simultaneously sequenced exc · gesturestate transient feedback with updating · parent child conflict resolution modifiers · custom gesture protocol and review checklist
- Use cases
- frontend · ui design
- Platforms
- macOS
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill swiftui-gesturesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.7k |
|---|---|
| repo stars | ★ 944 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 15, 2026 |
| Repository | dpearson2699/swift-ios-skills ↗ |
How do I add double-tap, drag, or pinch gestures to a SwiftUI view without parent-child conflicts?
Implement and review SwiftUI tap, drag, magnify, rotate, and composed gesture interactions with conflict resolution.
Who is it for?
iOS SwiftUI developers adding or reviewing touch gesture interactions on views.
Skip if: Skip for UIKit-only gesture code, Vision framework, or general SwiftUI layout without gestures.
When should I use this skill?
User asks about SwiftUI gestures, GestureState, magnify, drag, or gesture conflict resolution.
What you get
Working gesture modifiers with correct composition, GestureState feedback, and conflict resolution.
- SwiftUI gesture handler implementations
- Sequenced gesture state enum patterns
Files
SwiftUI Gestures (iOS 26+)
Review, write, and fix SwiftUI gesture interactions. Apply modern gesture APIs with correct composition, state management, and conflict resolution using Swift 6.3 patterns.
Scope boundary: This skill owns SwiftUI gesture recognition, composition, gesture state, and gesture-specific accessibility alternatives. Broader SwiftUI architecture/state ownership belongs in swiftui-patterns; list, scroll, form, and control layout belongs in swiftui-layout-components; broad UIKit bridging belongs in swiftui-uikit-interop.
When correcting Apple API availability, deprecation, or behavior claims, cite the relevant Sosumi or official Apple documentation URL in the response.
Contents
- Gesture Overview
- TapGesture
- LongPressGesture
- DragGesture
- MagnifyGesture (iOS 17+)
- RotateGesture (iOS 17+)
- Gesture Composition
- `@GestureState`
- Adding Gestures to Views
- Custom Gesture Protocol
- Common Mistakes
- Review Checklist
- References
Gesture Overview
| Gesture | Type | Value | Since |
|---|---|---|---|
TapGesture | Discrete | Void | iOS 13 |
LongPressGesture | Discrete | Bool | iOS 13 |
DragGesture | Continuous | DragGesture.Value | iOS 13 |
MagnifyGesture | Continuous | MagnifyGesture.Value | iOS 17 |
RotateGesture | Continuous | RotateGesture.Value | iOS 17 |
SpatialTapGesture | Discrete | SpatialTapGesture.Value | iOS 16 |
Discrete gestures fire once (.onEnded). Continuous gestures stream updates (.onChanged, .onEnded, .updating).
TapGesture
Recognizes one or more taps. Use the count parameter for multi-tap.
// Single, double, and triple tap
TapGesture() .onEnded { tapped.toggle() }
TapGesture(count: 2) .onEnded { handleDoubleTap() }
TapGesture(count: 3) .onEnded { handleTripleTap() }
// Shorthand modifier
Text("Tap me").onTapGesture(count: 2) { handleDoubleTap() }LongPressGesture
Succeeds after the user holds for minimumDuration. Fails if finger moves beyond maximumDistance.
// Basic long press (0.5s default)
LongPressGesture()
.onEnded { _ in showMenu = true }
// Custom duration and distance tolerance
LongPressGesture(minimumDuration: 1.0, maximumDistance: 10)
.onEnded { _ in triggerHaptic() }With visual feedback via @GestureState + .updating():
@GestureState private var isPressing = false
Circle()
.fill(isPressing ? .red : .blue)
.scaleEffect(isPressing ? 1.2 : 1.0)
.gesture(
LongPressGesture(minimumDuration: 0.8)
.updating($isPressing) { current, state, _ in state = current }
.onEnded { _ in completedLongPress = true }
)Shorthand: .onLongPressGesture(minimumDuration:perform:onPressingChanged:).
DragGesture
Tracks finger movement. Value provides startLocation, location, translation, velocity, and predictedEndTranslation. DragGesture.Value.velocity is available with DragGesture from iOS 13+; do not confuse it with iOS 17+ gesture types such as MagnifyGesture and RotateGesture.
@State private var offset = CGSize.zero
RoundedRectangle(cornerRadius: 16)
.fill(.blue)
.frame(width: 100, height: 100)
.offset(offset)
.gesture(
DragGesture()
.onChanged { value in offset = value.translation }
.onEnded { _ in withAnimation(.spring) { offset = .zero } }
)Configure minimum distance and coordinate space:
DragGesture(minimumDistance: 20, coordinateSpace: .global)MagnifyGesture (iOS 17+)
Replaces the deprecated MagnificationGesture. Tracks pinch-to-zoom scale.
@GestureState private var magnifyBy = 1.0
Image("photo")
.resizable().scaledToFit()
.scaleEffect(magnifyBy)
.gesture(
MagnifyGesture()
.updating($magnifyBy) { value, state, _ in
state = value.magnification
}
)With persisted scale:
@State private var currentScale = 1.0
@GestureState private var gestureScale = 1.0
Image("photo")
.scaleEffect(currentScale * gestureScale)
.gesture(
MagnifyGesture(minimumScaleDelta: 0.01)
.updating($gestureScale) { value, state, _ in state = value.magnification }
.onEnded { value in
currentScale = min(max(currentScale * value.magnification, 0.5), 5.0)
}
)RotateGesture (iOS 17+)
RotateGesture is the newer alternative to RotationGesture. Tracks two-finger rotation angle.
@State private var angle = Angle.zero
Rectangle()
.fill(.blue).frame(width: 200, height: 200)
.rotationEffect(angle)
.gesture(
RotateGesture(minimumAngleDelta: .degrees(1))
.onChanged { value in angle = value.rotation }
)With persisted rotation:
@State private var currentAngle = Angle.zero
@GestureState private var gestureAngle = Angle.zero
Rectangle()
.rotationEffect(currentAngle + gestureAngle)
.gesture(
RotateGesture()
.updating($gestureAngle) { value, state, _ in state = value.rotation }
.onEnded { value in currentAngle += value.rotation }
)Gesture Composition
.simultaneously(with:) — both gestures recognized at the same time
let magnify = MagnifyGesture()
.onChanged { value in scale = value.magnification }
let rotate = RotateGesture()
.onChanged { value in angle = value.rotation }
Image("photo")
.scaleEffect(scale)
.rotationEffect(angle)
.gesture(magnify.simultaneously(with: rotate))The value is SimultaneousGesture.Value with .first and .second optionals.
.sequenced(before:) — first must succeed before second begins
let longPressBeforeDrag = LongPressGesture(minimumDuration: 0.5)
.sequenced(before: DragGesture())
.onEnded { value in
guard case .second(true, let drag?) = value else { return }
finalOffset.width += drag.translation.width
finalOffset.height += drag.translation.height
}.exclusively(before:) — only one succeeds (first has priority)
let doubleTapOrLongPress = TapGesture(count: 2)
.exclusively(before:
LongPressGesture()
)
.onEnded { result in
switch result {
case .first(_): handleDoubleTap()
case .second(_): handleLongPress()
}
}@GestureState
@GestureState is a property wrapper that automatically resets to its initial value when the gesture ends. Use for transient feedback; use @State for values that persist.
@GestureState private var dragOffset = CGSize.zero // resets to .zero
@State private var position = CGSize.zero // persists
Circle()
.offset(
x: position.width + dragOffset.width,
y: position.height + dragOffset.height
)
.gesture(
DragGesture()
.updating($dragOffset) { value, state, _ in
state = value.translation
}
.onEnded { value in
position.width += value.translation.width
position.height += value.translation.height
}
)Custom reset with animation: @GestureState(resetTransaction: Transaction(animation: .spring))
Adding Gestures to Views
Three modifiers control gesture priority in the view hierarchy:
| Modifier | Behavior |
|---|---|
.gesture() | Lower precedence than gestures already defined by the view or its children. |
.highPriorityGesture() | Added gesture takes precedence over existing gestures. |
.simultaneousGesture() | Added gesture processes at the same priority as existing gestures. |
// Default: the child tap wins on the image; the parent handles empty stack space.
VStack {
Image(systemName: "star.fill")
.onTapGesture { handleChild() }
Rectangle().fill(.blue)
}
.gesture(TapGesture().onEnded { handleParent() })
// Use simultaneousGesture when both handlers should run on child content.
VStack {
Image(systemName: "star.fill")
.onTapGesture { handleChild() }
}
.simultaneousGesture(TapGesture().onEnded { handleParent() })
// Use highPriorityGesture only when the parent should win.
VStack {
Text("Child")
.gesture(TapGesture().onEnded { handleChild() })
}
.highPriorityGesture(TapGesture().onEnded { handleParent() })GestureMask
Control which gestures participate when using .gesture(_:including:):
.gesture(drag, including: .gesture) // added gesture; disables subview gestures
.gesture(drag, including: .subviews) // subview gestures; disables added gesture
.gesture(drag, including: .all) // default: added + subview gestures
.gesture(drag, including: .none) // disables added + subview gesturesCustom Gesture Protocol
Create reusable gestures by conforming to Gesture:
struct SwipeGesture: Gesture {
enum Direction { case left, right, up, down }
typealias Value = Direction
let minimumDistance: CGFloat
init(minimumDistance: CGFloat = 50) {
self.minimumDistance = minimumDistance
}
var body: AnyGesture<Direction> {
AnyGesture(
DragGesture(minimumDistance: minimumDistance)
.map { value in
let h = value.translation.width, v = value.translation.height
if abs(h) > abs(v) {
return h > 0 ? .right : .left
} else {
return v > 0 ? .down : .up
}
}
)
}
}
// Usage
Rectangle().gesture(SwipeGesture().onEnded { print("Swiped \($0)") })Wrap in a View extension for ergonomic API:
extension View {
func onSwipe(perform action: @escaping (SwipeGesture.Direction) -> Void) -> some View {
gesture(SwipeGesture().onEnded(action))
}
}Common Mistakes
1. Misreading parent/child gesture precedence
// DON'T: Assume parent .gesture() overrides the child tap
VStack {
Image(systemName: "star.fill")
.onTapGesture { childAction() }
}
.gesture(TapGesture().onEnded { parentAction() })
// DO: Pick the relationship explicitly
VStack {
Image(systemName: "star.fill")
.onTapGesture { childAction() }
}
.simultaneousGesture(TapGesture().onEnded { parentAction() })
// Or use .highPriorityGesture() when the parent should take precedence.2. Using @State instead of @GestureState for transient state
// DON'T: @State doesn't auto-reset — view stays offset after gesture ends
@State private var dragOffset = CGSize.zero
DragGesture()
.onChanged { value in dragOffset = value.translation }
.onEnded { _ in dragOffset = .zero } // manual reset required
// DO: @GestureState auto-resets when gesture ends
@GestureState private var dragOffset = CGSize.zero
DragGesture()
.updating($dragOffset) { value, state, _ in
state = value.translation
}3. Not using .updating() for intermediate feedback
// DON'T: No visual feedback during long press
LongPressGesture(minimumDuration: 2.0)
.onEnded { _ in showResult = true }
// DO: Provide feedback while pressing
@GestureState private var isPressing = false
LongPressGesture(minimumDuration: 2.0)
.updating($isPressing) { current, state, _ in
state = current
}
.onEnded { _ in showResult = true }4. Using deprecated gesture types on iOS 17+
// DON'T: Deprecated since iOS 17
MagnificationGesture() // deprecated — use MagnifyGesture()
// DO: Use newer gesture types
MagnifyGesture() // iOS 17+
RotateGesture() // iOS 17+ (newer alternative to RotationGesture)5. Heavy computation in onChanged
// DON'T: Expensive work called every frame (~60-120 Hz)
DragGesture()
.onChanged { value in
let result = performExpensiveHitTest(at: value.location)
let filtered = applyComplexFilter(result)
updateModel(filtered)
}
// DO: Throttle or defer expensive work
DragGesture()
.onChanged { value in
dragPosition = value.location // lightweight state update only
}
.onEnded { value in
performExpensiveHitTest(at: value.location) // once at end
}6. Using onTapGesture for actions that should be a Button
// DON'T: onTapGesture has no accessibility traits, VoiceOver role,
// Voice Control targeting, Switch Control scanning, or keyboard activation
Text("Delete")
.onTapGesture { deleteItem() }
// DO: Button provides all of these automatically
Button("Delete", role: .destructive) { deleteItem() }
// DO: For custom visuals, use ButtonStyle instead of onTapGesture
Button { toggleExpanded() } label: {
CardView()
}
.buttonStyle(.plain)Reserve onTapGesture for multi-tap (count: 2+), tap-location-dependent behavior, or adding tap recognition to non-interactive content that already has appropriate accessibility traits.
Review Checklist
- [ ] Correct gesture type:
MagnifyGesture/RotateGesture(not deprecatedMagnification/Rotationvariants) - [ ]
@GestureStateused for transient values that should reset;@Statefor persisted values - [ ]
.updating()provides intermediate visual feedback during continuous gestures - [ ] Parent/child conflicts resolved with
.highPriorityGesture()or.simultaneousGesture() - [ ]
onChangedclosures are lightweight — no heavy computation every frame - [ ] Composed gestures use correct combinator:
simultaneously,sequenced, orexclusively - [ ] Persisted scale/rotation clamped to reasonable bounds in
onEnded - [ ] Custom
Gestureconformances return a gesture body; useAnyGesture<Value>when mapping to a customValue - [ ] Gesture-driven animations use
.springor similar for natural deceleration - [ ]
GestureMaskconsidered when mixing gestures across view hierarchy levels - [ ]
onTapGestureonly used wherecount > 1, tap location, or coordinate space matters — plain single-tap actions useButtoninstead
References
- Read references/gesture-patterns.md when the task needs full drag-to-reorder, pinch-to-zoom, combined rotate+scale, velocity/projection, sequenced gesture state-machine, or gesture-specific UIKit interop examples.
- Gesture protocol
- TapGesture
- LongPressGesture
- DragGesture
- DragGesture.Value.velocity
- MagnifyGesture
- RotateGesture
- GestureState
- Composing SwiftUI gestures
- Adding interactivity with gestures
{
"skill_name": "swiftui-gestures",
"evals": [
{
"id": 0,
"name": "gesture-composition-precedence",
"prompt": "Review this SwiftUI interaction plan: a parent VStack uses .gesture(TapGesture()) and a child image uses .onTapGesture. The author says the parent always swallows the child tap, so they want to replace everything with highPriorityGesture. Explain the correct precedence model, when to use .gesture, .simultaneousGesture, .highPriorityGesture, and how GestureMask changes subview participation.",
"expected_output": "A correction-focused review that states .gesture has lower precedence than existing child/view gestures, uses simultaneous gestures only when both handlers should run, uses high priority only when the parent should win, and describes GestureMask cases accurately.",
"files": [],
"assertions": [
"States that .gesture attaches with lower precedence than gestures already defined by the view or its children, rather than saying it always swallows child gestures.",
"Explains .simultaneousGesture as the choice when parent and child handlers should both process the same interaction.",
"Explains .highPriorityGesture as the choice when the added parent gesture should take precedence over existing gestures.",
"Describes GestureMask .gesture, .subviews, .all, and .none in terms of enabling the added gesture and/or subview hierarchy gestures.",
"Keeps the answer focused on gesture conflict resolution and does not turn the task into broader navigation, layout, or architecture guidance."
]
},
{
"id": 1,
"name": "gesture-api-availability-review",
"prompt": "Audit this SwiftUI gesture guidance for iOS 26: use MagnificationGesture and RotationGesture because they are still the newest types, DragGesture.Value.velocity is only safe on iOS 17 and later, and UIGestureRecognizerRepresentable can be used on any iOS 16 SwiftUI screen. Give corrected modern guidance with availability notes.",
"expected_output": "A modern SwiftUI gesture availability review that recommends MagnifyGesture and RotateGesture for iOS 17+, identifies DragGesture.Value.velocity as available back to iOS 13, and treats UIGestureRecognizerRepresentable as iOS 18+ gesture-specific interop.",
"files": [],
"assertions": [
"Recommends MagnifyGesture instead of MagnificationGesture for iOS 17+ pinch/magnification work.",
"Recommends RotateGesture instead of RotationGesture for iOS 17+ rotation work.",
"Does not claim DragGesture.Value.velocity is iOS 17-only; identifies it as available on the same iOS 13+ baseline as DragGesture.Value.",
"Identifies UIGestureRecognizerRepresentable as iOS 18+ and limits it to UIKit gesture recognizer interop.",
"Uses Sosumi or official Apple documentation URLs when citing Apple API availability."
]
},
{
"id": 2,
"name": "gesture-boundary-accessibility",
"prompt": "A custom card grid uses onTapGesture for every delete button, drag gestures for reordering, a custom swipe recognizer, and then asks for navigation routing and grid layout cleanup in the same patch. Which parts belong in swiftui-gestures, what accessibility fixes should be made for gesture-only actions, and what should be handed to sibling skills?",
"expected_output": "A boundary-aware review that keeps gesture recognition/composition/accessibility alternatives in swiftui-gestures, changes plain tap actions into Buttons where appropriate, and routes layout, navigation, and broad state architecture to sibling skills.",
"files": [],
"assertions": [
"Keeps tap, drag, swipe recognition, gesture composition, GestureState, and gesture-specific accessibility alternatives in the swiftui-gestures scope.",
"Recommends Button or ButtonStyle for plain single-tap actions such as delete instead of onTapGesture-only controls.",
"Requires accessible alternatives such as accessibility actions for drag, swipe, or gesture-only interactions.",
"Routes grid/list/layout cleanup to swiftui-layout-components.",
"Routes navigation routing and destination modeling to swiftui-navigation, and broad state architecture to swiftui-patterns."
]
}
]
}
Gesture Patterns — Advanced Reference
Extended patterns for SwiftUI gesture handling. See the main SKILL.md for core APIs and common mistakes.
Contents
- Pinch-to-Zoom with MagnifyGesture
- Combined Rotate + Scale
- Drag-to-Reorder
- Gesture Velocity Calculations
- Long-Press then Drag
- SwiftUI + UIKit Gesture Interop
- Accessibility Considerations
Pinch-to-Zoom with MagnifyGesture
Full implementation with clamped scale, double-tap reset, and smooth animation:
struct PinchToZoomView: View {
@State private var currentScale = 1.0
@State private var currentOffset = CGSize.zero
@GestureState private var gestureScale = 1.0
@GestureState private var dragOffset = CGSize.zero
private let minScale = 0.5
private let maxScale = 5.0
var body: some View {
Image("photo")
.resizable()
.scaledToFit()
.scaleEffect(currentScale * gestureScale)
.offset(
x: currentOffset.width + dragOffset.width,
y: currentOffset.height + dragOffset.height
)
.gesture(magnifyGesture)
.simultaneousGesture(panGesture)
.onTapGesture(count: 2) {
withAnimation(.spring) {
currentScale = 1.0
currentOffset = .zero
}
}
}
private var magnifyGesture: some Gesture {
MagnifyGesture()
.updating($gestureScale) { value, state, _ in
state = value.magnification
}
.onEnded { value in
let newScale = currentScale * value.magnification
withAnimation(.spring) {
currentScale = min(max(newScale, minScale), maxScale)
}
}
}
private var panGesture: some Gesture {
DragGesture()
.updating($dragOffset) { value, state, _ in
guard currentScale > 1.0 else { return }
state = value.translation
}
.onEnded { value in
guard currentScale > 1.0 else { return }
currentOffset.width += value.translation.width
currentOffset.height += value.translation.height
}
}
}Combined Rotate + Scale
Simultaneous rotation and magnification for image editing:
struct RotateScaleView: View {
@State private var currentAngle = Angle.zero
@State private var currentScale = 1.0
@GestureState private var gestureAngle = Angle.zero
@GestureState private var gestureScale = 1.0
var body: some View {
Image("sticker")
.resizable()
.scaledToFit()
.frame(width: 200, height: 200)
.rotationEffect(currentAngle + gestureAngle)
.scaleEffect(currentScale * gestureScale)
.gesture(
RotateGesture()
.updating($gestureAngle) { value, state, _ in
state = value.rotation
}
.onEnded { value in
currentAngle += value.rotation
}
.simultaneously(with:
MagnifyGesture()
.updating($gestureScale) { value, state, _ in
state = value.magnification
}
.onEnded { value in
currentScale *= value.magnification
currentScale = min(max(currentScale, 0.3), 5.0)
}
)
)
}
}Drag-to-Reorder
Drag gesture with haptic feedback for list reordering:
struct ReorderableList: View {
@State private var items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
@State private var draggingItem: String?
@State private var dragOffset = CGSize.zero
var body: some View {
VStack {
ForEach(items, id: \.self) { item in
ItemRow(title: item, isDragging: draggingItem == item)
.offset(y: draggingItem == item ? dragOffset.height : 0)
.zIndex(draggingItem == item ? 1 : 0)
.gesture(
LongPressGesture(minimumDuration: 0.3)
.sequenced(before: DragGesture())
.onChanged { value in
switch value {
case .first(true):
withAnimation(.spring) {
draggingItem = item
}
case .second(true, let drag):
dragOffset = drag?.translation ?? .zero
updateOrder(for: item, translation: dragOffset.height)
default:
break
}
}
.onEnded { _ in
withAnimation(.spring) {
draggingItem = nil
dragOffset = .zero
}
}
)
}
}
}
private func updateOrder(for item: String, translation: CGFloat) {
guard let sourceIndex = items.firstIndex(of: item) else { return }
let rowHeight: CGFloat = 50
let offset = Int(translation / rowHeight)
let destinationIndex = min(max(sourceIndex + offset, 0), items.count - 1)
if sourceIndex != destinationIndex {
withAnimation(.spring) {
items.move(
fromOffsets: IndexSet(integer: sourceIndex),
toOffset: destinationIndex > sourceIndex
? destinationIndex + 1 : destinationIndex
)
}
}
}
}
struct ItemRow: View {
let title: String
let isDragging: Bool
var body: some View {
Text(title)
.frame(maxWidth: .infinity, minHeight: 46)
.background(isDragging ? Color.blue.opacity(0.2) : Color(.secondarySystemBackground))
.clipShape(.rect(cornerRadius: 8))
.shadow(radius: isDragging ? 4 : 0)
.scaleEffect(isDragging ? 1.05 : 1.0)
}
}Gesture Velocity Calculations
Use DragGesture.Value.velocity for the current drag velocity. Use predictedEndTranslation when you need a projection of where the drag would end if the user stopped now.
struct FlickDismissView: View {
@State private var offset = CGSize.zero
@State private var isDismissed = false
private let dismissThreshold: CGFloat = 200
private let velocityThreshold: CGFloat = 800
var body: some View {
if !isDismissed {
CardView()
.offset(y: offset.height)
.opacity(opacity)
.gesture(
DragGesture()
.onChanged { value in
if value.translation.height > 0 {
offset = value.translation
}
}
.onEnded { value in
let velocity = value.velocity.height
let distance = value.translation.height
if distance > dismissThreshold
|| velocity > velocityThreshold
{
withAnimation(.spring) {
isDismissed = true
}
} else {
withAnimation(.spring) {
offset = .zero
}
}
}
)
}
}
private var opacity: Double {
let progress = min(offset.height / dismissThreshold, 1.0)
return 1.0 - (progress * 0.5)
}
}Projection heuristic from predicted end translation:
DragGesture()
.onEnded { value in
// Approximate velocity from predicted vs actual
let predictedDelta = CGSize(
width: value.predictedEndTranslation.width - value.translation.width,
height: value.predictedEndTranslation.height - value.translation.height
)
let speed = sqrt(
predictedDelta.width * predictedDelta.width
+ predictedDelta.height * predictedDelta.height
)
if speed > 500 { handleFlick() }
}Long-Press then Drag (Sequenced Gesture with State Enum)
Model complex gesture states with an enum for clarity:
enum DragState {
case inactive
case pressing
case dragging(translation: CGSize)
var translation: CGSize {
switch self {
case .inactive, .pressing: return .zero
case .dragging(let t): return t
}
}
var isActive: Bool {
switch self {
case .inactive: return false
case .pressing, .dragging: return true
}
}
}
struct LongPressDragView: View {
@GestureState private var dragState = DragState.inactive
@State private var position = CGSize.zero
var body: some View {
Circle()
.fill(dragState.isActive ? .red : .blue)
.frame(width: 80, height: 80)
.shadow(radius: dragState.isActive ? 8 : 0)
.offset(
x: position.width + dragState.translation.width,
y: position.height + dragState.translation.height
)
.animation(.spring, value: dragState.isActive)
.gesture(
LongPressGesture(minimumDuration: 0.5)
.sequenced(before: DragGesture())
.updating($dragState) { value, state, _ in
switch value {
case .first(true):
state = .pressing
case .second(true, let drag):
state = .dragging(
translation: drag?.translation ?? .zero
)
default:
state = .inactive
}
}
.onEnded { value in
guard case .second(true, let drag?) = value else {
return
}
position.width += drag.translation.width
position.height += drag.translation.height
}
)
}
}SwiftUI + UIKit Gesture Interop
UIGestureRecognizerRepresentable (iOS 18+)
Bridge UIKit gesture recognizers into SwiftUI:
struct PinchGestureView: UIGestureRecognizerRepresentable {
@Binding var scale: CGFloat
func makeUIGestureRecognizer(context: Context) -> UIPinchGestureRecognizer {
UIPinchGestureRecognizer()
}
func handleUIGestureRecognizerAction(
_ recognizer: UIPinchGestureRecognizer,
context: Context
) {
switch recognizer.state {
case .changed:
scale = recognizer.scale
case .ended:
scale = recognizer.scale
recognizer.scale = 1.0
default:
break
}
}
}
// Usage in SwiftUI
struct ContentView: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Image("photo")
.scaleEffect(scale)
.gesture(PinchGestureView(scale: $scale))
}
}Using SwiftUI gestures in UIKit via UIHostingController
class GestureHostingController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swiftUIView = InteractiveCard()
let hostingController = UIHostingController(rootView: swiftUIView)
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.frame = view.bounds
hostingController.didMove(toParent: self)
}
}
struct InteractiveCard: View {
@GestureState private var dragOffset = CGSize.zero
var body: some View {
RoundedRectangle(cornerRadius: 16)
.fill(.blue.gradient)
.frame(width: 200, height: 300)
.offset(dragOffset)
.gesture(
DragGesture()
.updating($dragOffset) { value, state, _ in
state = value.translation
}
)
}
}Coordinating UIKit and SwiftUI gestures
When mixing gesture recognizers, use simultaneousGesture on the SwiftUI side and UIGestureRecognizerDelegate on the UIKit side to prevent conflicts:
// In your UIViewRepresentable coordinator
func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer
) -> Bool {
true // allow both UIKit and SwiftUI gestures to fire
}Accessibility Considerations
Always provide accessible alternatives for gesture-driven interactions:
Image("draggable")
.offset(offset)
.gesture(dragGesture)
.accessibilityAction(.default) { showAccessibleUI() }
.accessibilityAction(named: "Move up") {
withAnimation { offset.height -= 50 }
}
.accessibilityAction(named: "Move down") {
withAnimation { offset.height += 50 }
}Related skills
How it compares
Choose swiftui-gestures over generic SwiftUI docs when implementing multi-step or combined gestures like pinch-zoom with clamped bounds or sequenced long-press-drag.
FAQ
How do child gestures compete with parent scroll views?
Use highPriorityGesture or simultaneousGesture to control which gesture wins.
What replaced MagnificationGesture?
Use MagnifyGesture on iOS 17 plus; MagnificationGesture is deprecated.
When use GestureState vs State?
GestureState with updating resets automatically after gesture ends for transient feedback.
Is Swiftui Gestures safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.