UIGestureRecognizer就是为了识别用户的手势,一共六个细分的手势,分别是:点击(tap)、长按(longPress)、滑动(swipe)、缩放(pinch)、旋转(rotation)、拖拽(pan)。
UIGestureRecognizer:
1.state
typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
UIGestureRecognizerStatePossible,
UIGestureRecognizerStateBegan, // 手势开始识别
UIGestureRecognizerStateChanged, // 手势改变(过程中)
UIGestureRecognizerStateEnded, // 手势结束
UIGestureRecognizerStateCancelled, // 手势取消
UIGestureRecognizerStateFailed, // 手势失败
UIGestureRecognizerStateRecognized
};
2.locationInView
获取手势在视图中的位置
3.delegate
为了监听手势的各种行为
UITapGestureRecognizer(点击)
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
tapGesture.numberOfTouchesRequired = 1; //响应事件的手指数
tapGesture.numberOfTapsRequired = 1; //响应事件的点击次数
[self.view addGestureRecognizer:tapGesture];
UILongPressGestureRecognizer(长按)
UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
longGesture.minimumPressDuration = 1; //响应事件的最小时间
longGesture.allowableMovement = 50; //允许移动的距离范围
[self.view addGestureRecognizer:longGesture];
UISwipeGestureRecognizer(滑动)
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //滑动的方向
swipeGesture.numberOfTouchesRequired = 1;
[self.view addGestureRecognizer:swipeGesture];
UIPinchGestureRecognizer(缩放)
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
pinchGesture.scale = 2; //缩放的比例
[self.view addGestureRecognizer:pinchGesture];
UIRotationGestureRecognizer(旋转)
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)];
rotationGesture.rotation = M_PI_2;
[self.view addGestureRecognizer:rotationGesture];
-(void)rotationGesture:(id)sender{
UIRotateGestureRecognizer *gesture = sender;
if (gesture.state==UIGestureRecognizerStateChanged) {
_imageView.transform=CGAffineTransform=Rotation(_imageView.transform,gesture.rotation);
}
if (gesture.state==UIGestureRecognizerStateEnded) {
[UIView animateWithDuration:1 animations:^{
_imageView.transform=CGAffineTransformIdentity; //取消形变
}];
}
}
UIPanGestureRecognizer(拖拽)
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gesture:)];
panGesture.minimumNumberOfTouches = 1;
panGesture.maximumNumberOfTouches = 1;
[panGesture translationInView:self.view];
[_redView addGestureRecognizer:panGesture];