Skip to content

手势与冲突 ​

手势在 iOS 上几乎是命门——左右滑动、下拉刷新、长按预览、捏合缩放、双指旋转。SwiftUI 把 UIKit 的 UIGestureRecognizer 体系重新抽象成 Gesture 协议,语法干净了,但手势冲突仍然是这一篇最重要的话题。这一篇讲透:Gesture 体系、@GestureState 临时状态、组合(Simultaneous / Exclusive / HighPriority)、与 ScrollView / NavigationStack 滑动返回的冲突、onScrollGeometryChange(iOS 18+)。

一句话先记住:SwiftUI 的 Gesture 是值类型组合——TapGesture() / DragGesture() / LongPressGesture() 是手势描述,通过 .gesture(...) modifier 附加到 view 上,组合用 .simultaneously / .exclusively / .sequenced。冲突的本质是"父子手势谁先识别"——highPriorityGesture 让父先抢,simultaneousGesture 让两者同时识别。


一、基本手势 ​

swift
Text("点我")
    .onTapGesture { print("tap") }                      // 单击
    .onTapGesture(count: 2) { print("double") }         // 双击
    .onLongPressGesture { print("long press") }         // 长按

Text("拖我")
    .gesture(
        DragGesture()
            .onChanged { value in
                offset = value.translation
            }
            .onEnded { value in
                if abs(value.translation.width) > 100 {
                    // 滑过 100pt,触发某个操作
                }
                offset = .zero
            }
    )

.onTapGesture / .onLongPressGesture 是便捷方法,内部就是 TapGesture() / LongPressGesture() 配合 .gesture(...) modifier。

DragGesture 的 value 包含:

  • translation:从手势开始的偏移
  • location:当前位置(相对手势 view)
  • startLocation:起始位置
  • velocity:速度(iOS 17+)
  • predictedEndLocation:松手后预测落点(基于 velocity)
swift
DragGesture(minimumDistance: 10)   // 至少拖 10pt 才识别
    .onChanged { ... }

LongPressGesture(minimumDuration: 0.5, maximumDistance: 10)
    // 长按 0.5s,手指移动不超 10pt

二、@GestureState:手势期间的临时状态 ​

swift
struct DragCard: View {
    @GestureState private var dragOffset: CGSize = .zero
    
    var body: some View {
        Rectangle()
            .fill(.blue)
            .frame(width: 200, height: 100)
            .offset(dragOffset)
            .gesture(
                DragGesture()
                    .updating($dragOffset) { value, state, _ in
                        state = value.translation
                    }
            )
    }
}

@GestureState 是特殊的状态:手势进行中跟随手势更新,手势结束时自动重置为初始值。所以上面代码松手后 dragOffset 自动归零,Rectangle 弹回原位——不用写 onEnded { offset = .zero }。

updating(_:body:) 是 @GestureState 的对应回调,与 onChanged 区别:

  • onChanged:可以改 @State,改动持久
  • updating:只改 @GestureState,自动清零

典型用法:拖卡片预览时的临时偏移,手势结束自动归位;长按时的"按压感"缩放,松手即恢复。


三、手势组合 ​

swift
// SimultaneousGesture:两个同时识别
let drag = DragGesture()
let press = LongPressGesture()

view.gesture(
    drag.simultaneously(with: press)
)
.onChanged { value in
    // value.first  = drag's value
    // value.second = press's value
}
swift
// ExclusiveGesture:两个互斥,先识别的吃掉另一个
TapGesture().exclusively(before: DragGesture())
swift
// SequencedGesture:先后序列,前一个完成才能触发后一个
LongPressGesture(minimumDuration: 0.5)
    .sequenced(before: DragGesture())
    // 长按 0.5s 后才能拖
    .onEnded { value in
        switch value {
        case .first(_): break        // 只长按未拖
        case .second(_, let drag): break  // 长按 + 拖
        }
    }
组合何时用
simultaneously(with:)两个手势独立工作(双指放大 + 旋转同时)
exclusively(before:)一个识别后另一个不响应
sequenced(before:)"长按后拖" 这种顺序逻辑

四、父子手势冲突:三种 modifier ​

swift
// 默认 .gesture(...) —— 子视图先识别,父视图作为备份
parent.gesture(parentGesture) {
    child.gesture(childGesture)
}
// 子手势识别成功,父手势不触发

// .simultaneousGesture(...) —— 父与子同时识别,互不阻塞
parent.simultaneousGesture(parentGesture) {
    child.gesture(childGesture)
}

// .highPriorityGesture(...) —— 父手势优先,无视子手势
parent.highPriorityGesture(parentGesture) {
    child.gesture(childGesture)
}

实际场景:

swift
// 卡片上有一个按钮,卡片本身可滑动
Card {
    Button("详情") { showDetail() }
}
.gesture(
    DragGesture()
        .onChanged { offset = $0.translation }
)

按钮在卡片里,默认按钮的 tap 手势优先识别——点按钮时不会触发卡片滑动。但如果你想"滑动时只滑动,点击时才触发按钮",写法不变。

如果想 "卡片整体长按显示菜单,即使按钮上长按也响应":

swift
Card {
    Button("详情") { ... }
}
.highPriorityGesture(
    LongPressGesture(minimumDuration: 0.6)
        .onEnded { _ in showMenu() }
)
// 按钮上长按 0.6s 触发卡片菜单,而不是按钮

五、与 ScrollView 滑动的冲突 ​

ScrollView 内部已经有滑动手势,你在 ScrollView 内的子视图加 DragGesture 会冲突——ScrollView 滑动失败 / 子手势失败,二选一。

swift
ScrollView {
    LazyVStack {
        ForEach(items) { item in
            ItemRow(item: item)
                .gesture(DragGesture().onChanged { ... })   // ⚠️ 与 ScrollView 冲突
        }
    }
}

解决:

  1. 改用 swipeActions(对 List):
swift
List(items) { item in
    ItemRow(item: item)
        .swipeActions(edge: .trailing) {
            Button(role: .destructive) { delete(item) } label: { Text("删除") }
        }
}
  1. 限制 DragGesture 方向(把横向滑动留给 ScrollView):
swift
.gesture(
    DragGesture(minimumDistance: 30)    // 留够距离,30pt 后才识别
        .onChanged { value in
            // 只在横向滑动主导时响应
            if abs(value.translation.width) > abs(value.translation.height) * 2 {
                offset = value.translation.width
            }
        }
)
  1. simultaneousGesture 同时识别 ScrollView 与自定义手势(慎用,容易卡)。

六、NavigationStack 的返回手势冲突 ​

iPhone 上从左边缘 swipe 触发 NavigationStack 的 pop。如果你在屏幕左侧有自己的 DragGesture(比如抽屉、卡片左滑),会冲突。

swift
.gesture(
    DragGesture()
        .onChanged { ... }
)
// ⚠️ 用户从左边缘开始拖,系统返回手势被抢

解决:

  • 限制手势区域,避开左边缘:DragGesture(minimumDistance: 10) 加 if value.startLocation.x > 50 { ... }
  • 用 .toolbar(.hidden, for: .navigationBar) 隐藏 nav bar(系统不知道这是 NavigationStack 里,边缘 swipe 不响应)
  • iOS 18+ 用 .navigationBarBackButtonHidden + 自定义返回手势

七、捏合 / 旋转 / 拖动 三件套 ​

swift
@State private var scale: CGFloat = 1.0
@State private var rotation: Angle = .zero
@State private var offset: CGSize = .zero

Image("photo")
    .resizable()
    .scaledToFit()
    .scaleEffect(scale)
    .rotationEffect(rotation)
    .offset(offset)
    .gesture(
        SimultaneousGesture(
            SimultaneousGesture(
                MagnifyGesture()
                    .onChanged { value in scale = value.magnification },
                RotateGesture()
                    .onChanged { value in rotation = value.rotation }
            ),
            DragGesture()
                .onChanged { value in offset = value.translation }
        )
    )

MagnifyGesture(iOS 17+,旧 MagnificationGesture deprecated)与 RotateGesture(iOS 17+)是新版本。三种手势组合在一起,用户可以一手缩放 + 旋转 + 拖动,典型图片编辑器。


八、onScrollGeometryChange(iOS 18+):监听滚动位置 ​

swift
ScrollView {
    LazyVStack {
        ForEach(items) { ItemRow($0) }
    }
}
.onScrollGeometryChange(for: CGFloat.self) { geometry in
    geometry.contentOffset.y         // 滚动位置
} action: { oldValue, newValue in
    headerOpacity = max(0, 1 - newValue / 200)
}

iOS 18 之前要监听滚动位置得用 GeometryReader + PreferenceKey 一堆样板。onScrollGeometryChange 直接接收 ScrollGeometry,包含 contentOffset / containerSize / contentSize 等,声明式监听。

.scrollPosition(id:) 也是 iOS 18 新 API,绑定一个可观察的滚动位置 id,可用于实现"滚到某条 + 同步 UI":

swift
@State private var scrolledID: UUID?

ScrollView {
    LazyVStack {
        ForEach(items) { item in
            ItemRow(item: item).id(item.id)
        }
    }
    .scrollTargetLayout()
}
.scrollPosition(id: $scrolledID)

九、onTap 系列与 hitTesting ​

swift
.contentShape(.rect)   // 让透明区域也响应点击

Image 内有透明像素时,默认透明区域不响应点击。.contentShape(_:) 把整个 view 的"可点击区域"扩大到形状内全部。

swift
.allowsHitTesting(false)    // 完全不响应任何手势

某个视图想"显示但不响应交互"(比如 overlay 的指示器),用 .allowsHitTesting(false)。

swift
.onHover { isHovering in ... }    // macOS / Catalyst,iPad pointer
.focusable()                       // 可获焦点(键盘 / 遥控器)

iPad 接键盘鼠标时,.onHover 和 .focusable() 让你的 UI 支持指针交互。


十、踩坑 ​

  1. .onTapGesture 加在 Button 上——会覆盖 Button 的 tap,导致按钮 accessibility 丢失。Button 自己有 action,不要外面再 onTap。
  2. DragGesture 拖完没归零——onChanged 改的是 @State,松手不会自动重置。用 onEnded 归零,或者用 @GestureState + updating 自动归零。
  3. 手势放在 .background 视图上没响应——.background modifier 加的内容不参与命中测试。用 .overlay 或者把视图放在 ZStack 里。
  4. 同一个 view 加多个 .gesture(...)——后面的会覆盖前面的。要并存用组合手势 simultaneously(with:)。
  5. LongPressGesture 和 DragGesture 同时加上——长按手势被拖动取消,通常是想要的;但有时希望"长按后允许拖"用 sequenced。
  6. SimultaneousGesture 用 .onChanged——SimultaneousGesture 的 value 是 (First.Value, Second.Value) 元组,要拆开。
  7. 手势区域与 frame 不一致——.frame(width: 200) 之后 .padding(20) 加在前面,实际可点击区域是 frame + padding 全部,但 .gesture 加在 padding 之后只在原视图范围响应。手势 modifier 放在最外层(padding/frame 之后)。
  8. ScrollView 内自定义 swipe 永远不响应——ScrollView 的滑动手势抢占,改 swipeActions 或者用 .gesture 加 simultaneousGesture 配合方向判断。
  9. HighPriorityGesture 把按钮点不动——把所有子视图的 tap 都吃掉。慎用,只在确实需要"父优先"时。
  10. 手势相关状态用 @State 在拖动期间频繁触发 body 重算——body 频繁调用是常态,但如果 body 太重,改用 @GestureState(只在手势内有效)+ transform 等 modifier 而不是改布局参数。

下一篇 11-NavigationStack路由.md,讲 NavigationStack(path:) + NavigationLink(value:) + .navigationDestination(for:) 类型化路由、NavigationSplitView 双栏 / 三栏布局、NavigationView 为什么 deprecated、deep link 与 onOpenURL 桥接、路由状态可恢复、Tab 内嵌 NavigationStack 的边界。