UIGestureRecognizer 各个子类以及其作用
在 iOS 里,UIGestureRecognizer
是一个抽象基类,专门用来处理手势事件。它本身不能直接用,必须用它的 子类。这些子类分别对应常见的手势识别器。
常见的 UIGestureRecognizer
子类及作用
1. UITapGestureRecognizer
作用:点击手势(单击 / 双击)。
典型场景:点击按钮外区域关闭键盘、图片点击放大。
参数:可以设置
numberOfTapsRequired
(点击次数)、numberOfTouchesRequired
(手指数)。UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; tap.numberOfTapsRequired = 2; // 双击 tap.numberOfTouchesRequired = 1; // 单指 [view addGestureRecognizer:tap];
2. UILongPressGestureRecognizer
作用:长按手势。
典型场景:微信长按消息弹出菜单、长按图片保存。
参数:
minimumPressDuration
(按压时间,默认 0.5 秒),allowableMovement
(手指允许移动的范围)。UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 0.8; [view addGestureRecognizer:longPress];
3. UIPanGestureRecognizer
作用:拖拽手势(连续)。
典型场景:拖拽视图移动,滑动解锁。
方法:
translationInView:
获取手指相对位置,velocityInView:
获取速度。UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; [view addGestureRecognizer:pan];
4. UISwipeGestureRecognizer
作用:轻扫手势(单次)。
典型场景:左右滑动切换页面。
参数:
direction
(方向,可组合:UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight
)。UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; swipe.direction = UISwipeGestureRecognizerDirectionLeft; [view addGestureRecognizer:swipe];
5. UIPinchGestureRecognizer
作用:捏合手势(双指缩放)。
典型场景:图片缩放、地图缩放。
方法:
scale
(缩放倍数),可结合view.transform
。UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]; [view addGestureRecognizer:pinch];
6. UIRotationGestureRecognizer
作用:旋转手势(双指旋转)。
典型场景:图片旋转。
方法:
rotation
(旋转角度,弧度制)。UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)]; [view addGestureRecognizer:rotation];
总结对比
子类 | 作用 | 常用场景 |
---|---|---|
UITapGestureRecognizer | 单击 / 双击 | 点背景关闭键盘、点击放大 |
UILongPressGestureRecognizer | 长按 | 弹出菜单、保存图片 |
UIPanGestureRecognizer | 拖拽 | 拖动视图、滑动解锁 |
UISwipeGestureRecognizer | 轻扫 | 翻页、滑动删除 |
UIPinchGestureRecognizer | 捏合缩放 | 图片/地图缩放 |
UIRotationGestureRecognizer | 旋转 | 图片旋转 |
额外说明:
手势冲突处理:可以用
gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:
来允许多个手势并存。UIGestureRecognizer 基类:也提供了手势状态(
began / changed / ended / cancelled
),子类里都能用。