1、UIGestureRecognizer介绍
手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性。
iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了UIGestureRecognizer类。手势识别UIGestureRecognizer类是个抽象类,下面的子类是具体的手势,开发这可以直接使用这些手势识别。
- UITapGestureRecognizer 点击
- UIPinchGestureRecognizer 缩放
- UIRotationGestureRecognizer 旋转
- UISwipeGestureRecognizer 滑动
- UIPanGestureRecognizer 拖拽
- UILongPressGestureRecognizer 长按
手势可以分为“事件手势”与“状态手势”, 例如TapGesture指的点击的时候响应,是瞬间动作, 而panGesture指的拖拽, 只要状态是检测到是拖拽状态,都会响应回调方法。
UIGestureRecognizer的继承关系如下:
Gesture的状态
gesture.state :
- UIGestureRecognizerStateBegan
- UIGestureRecognizerStateChanged
- UIGestureRecognizerStateEnded
- UIGestureRecognizerStateCancelled
- UIGestureRecognizerStateFailed
常用:
swipeGesture的滑动方向值
swipGesture.direction ==
- UISwipeGestureRecognizerDirectionRight
- UISwipeGestureRecognizerDirectionLeft
- UISwipeGestureRecognizerDirectionUp
- UISwipeGestureRecognizerDirectionDown
CGPoint distanceSource = [sender translationInView:sender.view];
//获取拖拽手势的偏移量
CGFloat x = distanceSource.x;
CGFloat y = distanceSource.y;
CGPoint velocity = [sender velocityInView:sender.view];
//获取拖拽的X,Y方向速度
CGFloat speedX = velocity.x;
CGFloat speedY = velocity.y;
同时触发两个view的手势
手势之间是互斥的,如果你想同时触发两个view,那么需要实现协议 --
UIGestureRecognizerDelegate
并将以下方法返回设置为YES
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
//别忘了设置代理
panGestureRecognizer.delegate = self;
pinchGestureRecognizer.delegate = self;
rotateRecognizer.delegate = self;
手势依赖
<span style="font-size:14px;">[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];
</span>
上面的意思是, 当如果pan手势失败,就是没发生拖动,才会出发tap手势。