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
| 手勢 | iOS | macOS | visionOS |
|---|---|---|---|
| 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:跨平台應用程式的最佳實踐是什麼?
- 使用條件編譯 (
#if os(iOS)/#if os(macOS)) 處理平台特定的手勢 - 始終為無障礙功能添加
.accessibilityAction和鍵盤替代方案 - 在 UIKit/AppKit 視圖上測試手勢,以確保橋接相容性
- 使用
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+。