# 5.1 常见手势


<br>


## [TapGesture](https://developer.apple.com/documentation/swiftui/tapgesture)、[SpatialTapGesture](https://developer.apple.com/documentation/swiftui/spatialtapgesture)

要为视图添加点击手势，可以使用 [gesture(_:including:)](https://developer.apple.com/documentation/swiftui/view/gesture(_:including:)) 绑定一个 TapGesture 实例至视图，也可以直接在视图上使用 `.onTapGesture` 方法。

其它手势的添加方式类同，只不过相比 `.onTapGesture`、`.onLongPressGesture` 等直接为视图绑定手势的方法，`gesture(_:including:)` 提供了更多灵活性，如手势的复用、手势的状态监听等。

`.onTapGesture` 有以下两个可选的方法：

```swift
// iOS 13.0+, macOS 10.15+
func onTapGesture(
    count: Int = 1,
    perform action: @escaping () -> Void
) -> some View

// iOS 16.0+, macOS 13.0+
func onTapGesture(
    count: Int = 1,
    coordinateSpace: CoordinateSpace = .local,
    perform action: @escaping (CGPoint) -> Void
) -> some View
```

`count` 参数可以控制点击的次数，`coordinateSpace` 表示点击位置的参考坐标系，关于 CoordinateSpace 可以参考 《共享布局信息》 中关于  GeometryReader 部分的介绍。

SpatialTapGesture 是 iOS 16.0/macOS 13.0 新推出的特性，它能够方便地获取点击的位置信息和复用点击手势。从上面的代码中可以看到，其实 `.onTapGesture` 从 iOS 16.0/macOS 13.0 之后也支持获取位置信息了，可以认为 SpatialTapGesture 是一个特殊的 TapGesture。

<span style="background: #007BFF; color: white; padding: 3px 10px; border-radius: 5px">> 查看示例</span>

## [LongPressGesture](https://developer.apple.com/documentation/swiftui/longpressgesture)

长按手势支持自定义时长、移动距离，如下方法中 `minimumDuration` 参数表示长按的最短时间，`maximumDistance` 表示长按时移动的最大距离，如果时长不够或者移动距离超出最大距离，都无法激活长按事件。

```swift
func onLongPressGesture(
    minimumDuration: Double = 0.5,
    maximumDistance: CGFloat = 10,
    perform action: @escaping () -> Void,
    onPressingChanged: ((Bool) -> Void)? = nil
) -> some View
```

## [DragGesture](https://developer.apple.com/documentation/swiftui/draggesture)

拖拽手势可以通过 `.onChanged` 和 `.onEnded` 分别监听手势的变化和结束，其它手势类似，几乎都可以使用这两个方法进行状态监听。

```swift
private var drag: some Gesture {
  DragGesture()
    .onChanged { v in
      withAnimation {
        offset = v.translation
      }
    }
    .onEnded { v in
      withAnimation {
        offset = .zero
      }
    }
}
```

## [MagnificationGesture](https://developer.apple.com/documentation/swiftui/magnificationgesture)

MagnificationGesture 用于双指缩放，如果是 iOS 设备，直接使用双指在屏幕上缩放，如果是 mac，使用触摸板才能进行缩放。

## [RotationGesture](https://developer.apple.com/documentation/swiftui/rotationgesture)

RotationGesture 用于旋转，与 MagnificationGesture 类似。




---

> 作者: 宋明  
> URL: https://apolla.cc/posts/swiftui-eul/5.1-%E5%B8%B8%E8%A7%81%E6%89%8B%E5%8A%BF/  

