Communitygithub.com

SwiftUI 手勢指南

實現 SwiftUI 手勢(點按、拖曳、長按、縮放、旋轉)、組合手勢、管理手勢狀態或除錯手勢衝突時使用——包含手勢辨識、組合、無障礙支援及跨平台支援的全面模式。

SwiftUI 手勢指南 是什麼?

這個技能提供了一套完整的 SwiftUI 手勢開發指南,涵蓋從基本手勢辨識到高階組合與自訂手勢的各種模式。它詳細說明了如何使用 TapGesture、DragGesture、LongPressGesture、MagnificationGesture 和 RotationGesture,並強調了正確的狀態管理方式,例如使用 @GestureState 處理臨時狀態以避免畫面卡頓或狀態未重置的問題。更重要的是,技能深入探討了手勢組合的策略:.simultaneously 用於同時執行多個手勢、.sequenced 用於依序觸發、.exclusively 用於確保只有一個手勢被響應,這對於解決複雜互動中的手勢衝突至關重要。此外,技能也提供了無障礙整合的最佳實踐,包括為 VoiceOver 使用者添加 .accessibilityAdjustableAction 以及為 macOS 提供鍵盤替代方案,並考慮了跨平台(iOS、macOS、visionOS)的差異。開發者可以透過這份指南快速診斷常見問題,如拖曳無反應、雙擊觸發點按、或手勢狀態無法重置,並獲得可立即套用的解決方案。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-gestures

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

SwiftUI 手勢指南 是做什麼的?

全面的 SwiftUI 手勢辨識指南,包含組合模式、狀態管理和無障礙整合。

何時使用此技能

  • 實作點按、拖曳、長按、縮放或旋轉手勢
  • 組合多個手勢(同時、依序、獨佔)
  • 使用 GestureState 管理手勢狀態
  • 建立自訂手勢辨識器
  • 除錯手勢衝突或無響應的手勢
  • 讓手勢支援 VoiceOver 無障礙功能
  • 跨平台手勢處理(iOS、macOS、visionOS)

範例提示

以下是開發者常問的真實問題,此技能旨在回答這些問題:

1. "我的拖曳手勢無法作用——拖曳時畫面沒有移動。該如何除錯?"

→ 此技能涵蓋 DragGesture 狀態管理模式,並展示如何使用 @GestureState 正確更新檢視偏移。

2. "我在同一個檢視上同時有點按手勢和拖曳手勢。點按可以運作,但拖曳不行。該如何修復?"

→ 此技能示範如何使用 .simultaneously、.sequenced 和 .exclusively 進行手勢組合,以解決手勢衝突。

3. "我希望使用者先長按才能拖曳項目。該如何串接手勢?"

→ 此技能展示如何使用 .sequenced 模式,以正確順序組合 LongPressGesture 和 DragGesture。

4. "我的手勢狀態在手勢結束時沒有重置。檢視卡在錯誤的位置。"

→ 此技能涵蓋 @GestureState 的自動重置行為,以及使用 updating 參數進行正確的狀態管理。

5. "使用 VoiceOver 的使用者無法存取需要手勢的功能。如何讓手勢具備無障礙性?"

→ 此技能示範 .accessibilityAction 模式,並為 VoiceOver 使用者提供替代互動方式。


選擇正確的手勢(決策樹)

你需要什麼互動?

├─ 單次點按/點擊?
│  └─ 使用 Button(優先)或 TapGesture
│
├─ 拖曳/平移移動?
│  └─ 使用 DragGesture
│
├─ 按住後再執行動作?
│  └─ 使用 LongPressGesture
│
├─ 捏合縮放?
│  └─ 使用 MagnificationGesture
│
├─ 兩指旋轉?
│  └─ 使用 RotationGesture
│
├─ 多個手勢一起使用?
│  ├─ 同時進行? → .simultaneously
│  ├─ 一個接一個? → .sequenced
│  └─ 二選一? → .exclusively
│
└─ 複雜的自訂行為?
   └─ 建立符合 Gesture 協定的自訂手勢

模式 1:基本手勢辨識

TapGesture

❌ 錯誤(在非語義檢視上自訂點按)

Text("Submit")
  .onTapGesture {
    submitForm()
  }

問題:

  • VoiceOver 不會將其宣告為按鈕
  • 沒有視覺按壓回饋
  • 不尊重無障礙設定

✅ 正確(使用 Button 處理點按動作)

Button("Submit") {
  submitForm()
}
.buttonStyle(.bordered)

何時使用 TapGesture:僅當你需要點按的數據(位置、次數)或非標準點按行為時:

Image("map")
  .onTapGesture(count: 2) { // 雙擊顯示詳細資訊
    showDetails()
  }
  .onTapGesture { location in // 單次點按以固定位置
    addPin(at: location)
  }

DragGesture

❌ 錯誤(在手勢中直接變異狀態)

@State private var offset = CGSize.zero

var body: some View {
  Circle()
    .offset(offset)
    .gesture(
      DragGesture()
        .onChanged { value in
          offset = value.translation // ❌ 每一幀都更新,造成卡頓
        }
    )
}

問題:

  • 每次拖曳事件都會更新檢視(每秒 60-120 次)
  • 無法重置到原始位置
  • 若拖曳被取消,會遺失中間狀態

✅ 正確(使用 GestureState 處理臨時狀態)

@GestureState private var dragOffset = CGSize.zero
@State private var position = CGSize.zero

var body: some View {
  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
        }
    )
}

原因:GestureState 在手勢結束時會自動重置為初始值,防止狀態損壞。


LongPressGesture

@GestureState private var isDetectingLongPress = false
@State private var completedLongPress = false

var body: some View {
  Text("按住不放")
    .foregroundStyle(isDetectingLongPress ? .red : .blue)
    .gesture(
      LongPressGesture(minimumDuration: 1.0)
        .updating($isDetectingLongPress) { currentState, gestureState, _ in
          gestureState = currentState // 按住期間的視覺回饋
        }
        .onEnded { _ in
          completedLongPress = true // 按住後的動作
        }
    )
}

關鍵參數:

  • minimumDuration:需按住多久(預設 0.5 秒)
  • maximumDistance:手指在取消前可移動的距離(預設 10 點)

MagnificationGesture

@GestureState private var magnificationAmount = 1.0
@State private var currentZoom = 1.0

var body: some View {
  Image("photo")
    .scaleEffect(currentZoom * magnificationAmount)
    .gesture(
      MagnificationGesture()
        .updating($magnificationAmount) { value, state, _ in
          state = value.magnification
        }
        .onEnded { value in
          currentZoom *= value.magnification
        }
    )
}

平台說明:

  • iOS:兩指捏合手勢
  • macOS:觸控板捏合
  • visionOS:3D 空間中的捏合手勢

RotationGesture

@GestureState private var rotationAngle = Angle.zero
@State private var currentRotation = Angle.zero

var body: some View {
  Rectangle()
    .fill(.blue)
    .frame(width: 200, height: 200)
    .rotationEffect(currentRotation + rotationAngle)
    .gesture(
      RotationGesture()
        .updating($rotationAngle) { value, state, _ in
          state = value.rotation
        }
        .onEnded { value in
          currentRotation += value.rotation
        }
    )
}

模式 2:手勢組合

同時手勢

使用時機:兩個手勢應同時運作

@GestureState private var dragOffset = CGSize.zero
@GestureState private var magnificationAmount = 1.0

var body: some View {
  Image("photo")
    .offset(dragOffset)
    .scaleEffect(magnificationAmount)
    .gesture(
      DragGesture()
        .updating($dragOffset) { value, state, _ in
          state = value.translation
        }
        .simultaneously(with:
          MagnificationGesture()
            .updating($magnificationAmount) { value, state, _ in
              state = value.magnification
            }
        )
    )
}

使用案例:照片檢視器,可同時拖曳和捏合縮放。


依序手勢

使用時機:一個手勢必須完成後,下一個才能開始

@State private var isLongPressing = false
@GestureState private var dragOffset = CGSize.zero

var body: some View {
  Circle()
    .offset(dragOffset)
    .gesture(
      LongPressGesture(minimumDuration: 0.5)
        .onEnded { _ in
          isLongPressing = true
        }
        .sequenced(before:
          DragGesture()
            .updating($dragOffset) { value, state, _ in
              state = value.translation
            }
            .onEnded { _ in
              isLongPressing = false
            }
        )
    )
}

使用案例:iOS 主畫面 — 長按進入編輯模式,然後拖曳重新排序。


獨佔手勢

使用時機:只有一個手勢應該勝出,而非兩者

var body: some View {
  Rectangle()
    .gesture(
      TapGesture(count: 2) // 雙擊
        .onEnded { _ in
          zoom()
        }
        .exclusively(before:
          TapGesture(count: 1) // 單擊
            .onEnded { _ in
              select()
            }
        )
    )
}

原因:沒有 .exclusively 時,雙擊會觸發同時觸發單擊和雙擊處理器。

運作原理:SwiftUI 會等待是否有第二次點擊到來。如果有 → 雙擊勝出。如果沒有 → 單擊勝出。


模式 3:GestureState 與 State 的比較

何時使用哪一種

使用情境狀態類型原因
手勢期間的臨時回饋@GestureState手勢結束時自動重置
最終提交的值@State手勢結束後仍會保留
手勢期間的動畫@GestureState流暢的轉場效果
資料持久化@State在檢視更新後仍存在

完整範例:可拖曳卡片

struct DraggableCard: View {
  @GestureState private var dragOffset = CGSize.zero // 臨時
  @State private var position = CGSize.zero          // 永久

  var body: some View {
    RoundedRectangle(cornerRadius: 12)
      .fill(.blue)
      .frame(width: 300, height: 200)
      .offset(
        x: position.width + dragOffset.width,
        y: position.height + dragOffset.height
      )
      .gesture(
        DragGesture()
          .updating($dragOffset) { value, state, transaction in
            state = value.translation

            // 啟用動畫以獲得流暢回饋
            transaction.animation = .interactiveSpring()
          }
          .onEnded { value in
            // 使用動畫提交最終位置
            withAnimation(.spring()) {
              position.width += value.translation.width
              position.height += value.translation.height
            }
          }
      )
  }
}

關鍵洞察:GestureState 的第三個參數 transaction 可讓你在手勢期間自訂動畫。


模式 4:自訂手勢

何時建立自訂手勢

  • 需要內建手勢未提供的行為
  • 想要封裝複雜的手勢邏輯
  • 在多個檢視間重複使用手勢

範例:具有方向性的滑動手勢

struct SwipeGesture: Gesture {
  enum Direction {
    case left, right, up, down
  }

  let minimumDistance: CGFloat
  let coordinateSpace: CoordinateSpace

  init(minimumDistance: CGFloat = 50, coordinateSpace: CoordinateSpace = .local) {
    self.minimumDistance = minimumDistance
    self.coordinateSpace = coordinateSpace
  }

  // Value 是方向
  typealias Value = Direction

  // Body 建立在 DragGesture 之上
  var body: AnyGesture<Direction> {
    DragGesture(minimumDistance: minimumDistance, coordinateSpace: coordinateSpace)
      .map { value in
        let horizontal = value.translation.width
        let vertical = value.translation.height

        if abs(horizontal) > abs(vertical) {
          return horizontal < 0 ? .left : .right
        } else {
          return vertical < 0 ? .up : .down
        }
      }
      .eraseToAnyGesture()
  }
}

// 用法
Text("滑動我")
  .gesture(
    SwipeGesture()
      .onEnded { direction in
        switch direction {
        case .left: deleteItem()
        case .right: archiveItem()
        default: break
        }
      }
  )

模式 5:手勢速度和預測

存取速度

@State private var velocity: CGSize = .zero

var body: some View {
  Circle()
    .gesture(
      DragGesture()
        .onEnded { value in
          // value.velocity 在 iOS 18+ 已棄用
          // 使用 value.predictedEndLocation 和時間

          let timeDelta = value.time.timeIntervalSince(value.startLocation.time)
          let distance = value.translation

          velocity = CGSize(
            width: distance.width / timeDelta,
            height: distance.height / timeDelta
          )

          // 使用動量進行動畫
          withAnimation(.interpolatingSpring(stiffness: 100, damping: 15)) {
            applyMomentum(velocity: velocity)
          }
        }
    )
}

預測結束位置(iOS 16+)

DragGesture()
  .onChanged { value in
    // 根據速度預測手勢可能結束的位置
    let predicted = value.predictedEndLocation

    // 顯示項目將落地的預覽
    showPreview(at: predicted)
  }

使用案例:彈性物理效果、動量滾動、拋擲動畫。


模式 6:無障礙整合

讓自訂手勢具備無障礙性

❌ 錯誤(僅限手勢,無 VoiceOver 支援)

Image("slider")
  .gesture(
    DragGesture()
      .onChanged { value in
        updateVolume(value.translation.width)
      }
  )

問題:VoiceOver 使用者無法調整滑桿。

✅ 正確(加入無障礙動作)

@State private var volume: Double = 50

var body: some View {
  Image("slider")
    .gesture(
      DragGesture()
        .onChanged { value in
          volume = calculateVolume(from: value.translation.width)
        }
    )
    .accessibilityElement()
    .accessibilityLabel("音量")
    .accessibilityValue("\(Int(volume))%")
    .accessibilityAdjustableAction { direction in
      switch direction {
      case .increment:
        volume = min(100, volume + 5)
      case .decrement:
        volume = max(0, volume - 5)
      @unknown default:
        break
      }
    }
}

原因:VoiceOver 使用者現在可以向上/向下滑動來調整音量,而無需看到或使用該手勢。

鍵盤替代方案(macOS)

Rectangle()
  .gesture(
    DragGesture()
      .onChanged { value in
        move(by: value.translation)
      }
  )
  .onKeyPress(.upArrow) {
    move(by: CGSize(width: 0, height: -10))
    return .handled
  }
  .onKeyPress(.downArrow) {
    move(by: CGSize(width: 0, height: 10))
    return .handled
  }
  .onKeyPress(.leftArrow) {
    move(by: CGSize(width: -10, height: 0))
    return .handled
  }
  .onKeyPress(.rightArrow) {
    move(by: CGSize(width: 10, height: 0))
    return .handled
  }

模式 7:跨平台手勢

iOS vs macOS vs visionOS

手勢iOSmacOSvisionOS
TapGesture手指點按滑鼠點擊/觸控板點按手指(手部追蹤)點按
DragGesture手指拖曳滑鼠拖曳/觸控板拖曳捏合並拖曳(在 3D 空間中)
LongPressGesture長按手指長按滑鼠/觸控板手指捏合手勢
MagnificationGesture兩指捏合觸控板捏合捏合手勢(3D 空間中)
RotationGesture兩指旋轉觸控板旋轉虛擬物件旋轉(手勢重映射)

平台特定考量

  • iOS:使用點(points),謹慎處理避開安全區域和動態島
  • macOS:修改器使用 Option/Command 鍵,使用 .onKeyPress 添加鍵盤替代方案
  • visionOS:空間輸入(凝視 + 捏合),添加 .handGesture 進行手勢辨識,Unity 手勢的 3D 邊界

常見問題(FAQ)

Q:如何除錯無響應的手勢?

// 1. 檢查視圖層級 — 哪個視圖在「攔截」手勢?
// 使用 .onTapGesture 測試
Circle()
  .onTapGesture { print("Tapped") }

// 2. 確認手勢修飾符順序
// ❌ 錯誤:gesture 之後的修飾符位於手勢之上
Circle()
  .gesture(dragGesture)
  .onTapGesture { } // 永遠不會觸發!

// ✅ 正確:先加入所有修飾符,再附加手勢
Circle()
  .foregroundStyle(.blue)
  .frame(width: 100, height: 100)
  .gesture(dragGesture) // 最後加入

Q:為什麼我的 GestureState 沒有重置?

  • 確認你使用的是 @GestureState,而不是 @State
  • 檢查 GestureState 是否宣告為 private
  • 找出可能阻止重置的 onEnded 處理器中的副作用

Q:如何讓手勢與動畫一起流暢運作?

// 使用 .interactiveSpring() 實現即時反饋
DragGesture()
  .updating($dragOffset) { value, state, transaction in
    state = value.translation
    transaction.animation = .interactiveSpring()
  }

// 使用 .spring() 實現優雅的結束動畫
.onEnded { value in
  withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) {
    commitPosition(value.translation)
  }
}

Q:跨平台應用程式的最佳實踐是什麼?

  1. 使用條件編譯 (#if os(iOS) / #if os(macOS)) 處理平台特定的手勢
  2. 始終為無障礙功能添加 .accessibilityAction 和鍵盤替代方案
  3. 在 UIKit/AppKit 視圖上測試手勢,以確保橋接相容性
  4. 使用 UIGestureRecognizer 表示協定橋接舊版手勢

進階主題

手勢優先級

// 高優先級手勢 (higherPriority)
Circle()
  .highPriorityGesture(  // 將在低優先級手勢之前被辨識
    TapGesture().onEnded { print("High") }
  )
  .gesture(
    TapGesture().onEnded { print("Low") }
  )

子視圖手勢優先級

VStack {
  Circle()
    .onTapGesture { print("Child tapped") } // 子視圖先接收
  Text("Hello")
}
.onTapGesture { print("Parent tapped") } // 若子視圖未處理才會觸發

合約模式(SwiftUI 專家)

// 手勢協定:用於可測試和可重複使用的手勢邏輯
protocol GestureContract {
  associatedtype Value: Equatable
  var gesture: AnyGesture<Value> { get }
}

struct LongPressThenDragContract: GestureContract {
  var gesture: AnyGesture<GestureState<CGSize>> {
    LongPressGesture(minimumDuration: 0.5)
      .sequenced(before: DragGesture())
      .map { phase in
        // 將序列相位映射到最終狀態
      }
      .eraseToAnyGesture()
  }
}

版本相容性

SwiftUI 版本可用手勢新增內容
iOS 13+TapGesture, DragGesture, LongPressGesture, MagnificationGesture, RotationGesture初始手勢辨識
iOS 14+手勢組合.simultaneously, .sequenced, .exclusively
iOS 15+無障礙焦點無障礙增強
iOS 16+預測結束位置predictedEndLocation
iOS 17+3D 手勢visionOS 手勢
iOS 18+動畫交易transaction 動畫改進

撰寫者

使用 AI 代理程式輔助,由 Apple 開發者社群提供支援。針對 SwiftUI 5、iOS 18+、macOS 15+、visionOS 2+。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能