Swiftui Gestures

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

Implement, review, or improve SwiftUI gesture handling. Use when adding tap, long press, drag, magnify, or rotate gestures, composing gestures with simultaneously/sequenced/exclusively, managing transient state with @GestureState, resolving parent/child gesture conflicts with highPriorityGesture or simultaneousGesture, building custom Gesture protocol conformances, or migrating from deprecated MagnificationGesture to MagnifyGesture or using the newer RotateGesture.

AI 產生的概覽

指導實作、審查與修正 SwiftUI 手勢處理、組合、狀態與衝突解決。

功能
此技能為撰寫與審查 SwiftUI 手勢程式碼提供參考指引,涵蓋點擊、長按、拖曳、縮放與旋轉手勢。它說明使用 simultaneously、sequenced 與 exclusively 進行手勢組合,使用 @GestureState 管理暫時狀態,以及透過 highPriorityGesture 或 simultaneousGesture 解決父子手勢衝突。它也涵蓋自訂 Gesture 協定實作、已棄用 API 遷移、常見錯誤與審查清單。
適用情境
在新增或除錯 SwiftUI 手勢(例如點擊、長按、拖曳、捏合或旋轉)時使用。它也適合審查手勢組合、手勢狀態或父子手勢衝突,以及從已棄用的 MagnificationGesture 或 RotationGesture API 遷移。
執行需求
沒有指令碼,僅為說明性內容。它引用一個選用的手勢模式參考檔案,並在涉及 API 可用性時引用 Apple 文件連結。

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

GestureTypeValueSince
TapGestureDiscreteVoidiOS 13
LongPressGestureDiscreteBooliOS 13
DragGestureContinuousDragGesture.ValueiOS 13
MagnifyGestureContinuousMagnifyGesture.ValueiOS 17
RotateGestureContinuousRotateGesture.ValueiOS 17
SpatialTapGestureDiscreteSpatialTapGesture.ValueiOS 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.

swift
// Single, double, and triple tapTapGesture()            .onEnded { tapped.toggle() }TapGesture(count: 2)    .onEnded { handleDoubleTap() }TapGesture(count: 3)    .onEnded { handleTripleTap() }
// Shorthand modifierText("Tap me").onTapGesture(count: 2) { handleDoubleTap() }

LongPressGesture

Succeeds after the user holds for minimumDuration. Fails if finger moves beyond maximumDistance.

swift
// Basic long press (0.5s default)LongPressGesture()    .onEnded { _ in showMenu = true }
// Custom duration and distance toleranceLongPressGesture(minimumDuration: 1.0, maximumDistance: 10)    .onEnded { _ in triggerHaptic() }

With visual feedback via @GestureState + .updating():

swift
@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.

swift
@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:

swift
DragGesture(minimumDistance: 20, coordinateSpace: .global)

MagnifyGesture (iOS 17+)

Replaces the deprecated MagnificationGesture. Tracks pinch-to-zoom scale.

swift
@GestureState private var magnifyBy = 1.0
Image("photo")    .resizable().scaledToFit()    .scaleEffect(magnifyBy)    .gesture(        MagnifyGesture()            .updating($magnifyBy) { value, state, _ in                state = value.magnification            }    )

RotateGesture (iOS 17+)

RotateGesture is the newer alternative to RotationGesture. Tracks two-finger rotation angle.

swift
@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 }    )

For persisted, clamped magnification and combined rotation examples, load references/gesture-patterns.md [blocked].

Gesture Composition

.simultaneously(with:) — both gestures recognized at the same time

swift
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

swift
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)

swift
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.

swift
@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:

ModifierBehavior
.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.
swift
let parentTap = TapGesture().onEnded { handleParent() }
VStack {    Image(systemName: "star.fill")        .onTapGesture { handleChild() }}.simultaneousGesture(parentTap) // Both handlers run on child content.

Use .gesture(parentTap) for the default lower-precedence parent gesture, or .highPriorityGesture(parentTap) when the added parent gesture should win.

GestureMask

Control which gestures participate when using .gesture(_:including:):

swift
.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 gestures

Custom Gesture Protocol

Create reusable gestures by conforming to Gesture:

swift
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                    }                }        )    }}
// UsageRectangle().gesture(SwipeGesture().onEnded { print("Swiped \($0)") })

Wrap in a View extension for ergonomic API:

swift
extension View {    func onSwipe(perform action: @escaping (SwipeGesture.Direction) -> Void) -> some View {        gesture(SwipeGesture().onEnded(action))    }}

Common Mistakes

1. Misreading parent/child gesture precedence

Do not assume a parent .gesture() overrides child gestures. Choose the relationship explicitly as shown in Adding Gestures to Views.

2. Using @State instead of @GestureState for transient state

Use @GestureState for values that should reset when recognition ends; keep persistent results in @State. See @GestureState.

3. Not using .updating() for intermediate feedback

swift
// DON'T: No visual feedback during long pressLongPressGesture(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+

swift
// DON'T: Deprecated since iOS 17MagnificationGesture()   // deprecated — use MagnifyGesture()
// DO: Use newer gesture typesMagnifyGesture()         // iOS 17+RotateGesture()          // iOS 17+ (newer alternative to RotationGesture)

5. Heavy computation in onChanged

swift
// 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 workDragGesture()    .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

swift
// DON'T: onTapGesture has no accessibility traits, VoiceOver role,// Voice Control targeting, Switch Control scanning, or keyboard activationText("Delete")    .onTapGesture { deleteItem() }
// DO: Button provides all of these automaticallyButton("Delete", role: .destructive) { deleteItem() }
// DO: For custom visuals, use ButtonStyle instead of onTapGestureButton { 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 deprecated Magnification/Rotation variants)
  • @GestureState used for transient values that should reset; @State for persisted values
  • .updating() provides intermediate visual feedback during continuous gestures
  • Parent/child conflicts resolved with .highPriorityGesture() or .simultaneousGesture()
  • onChanged closures are lightweight — no heavy computation every frame
  • Composed gestures use correct combinator: simultaneously, sequenced, or exclusively
  • Persisted scale/rotation clamped to reasonable bounds in onEnded
  • Custom Gesture conformances return a gesture body; use AnyGesture<Value> when mapping to a custom Value
  • Gesture-driven animations use .spring or similar for natural deceleration
  • GestureMask considered when mixing gestures across view hierarchy levels
  • onTapGesture only used where count > 1, tap location, or coordinate space matters — plain single-tap actions use Button instead

References

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/swiftui-gestures提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新