1、创建手势识别器,并添加到视图中
创建手势识别器,其中参数 initWithTarget 指出了处理手势的对象,参数 action 指出了处理手势的方法名。
UIPinchGestureRecognizer *pinchRecognizer=
[[UIPinchGestureRecognizer alloc] initWithTarget:self
action:@selector(pinchView:)];
[self.view addGestureRecognizer:pinchRecognizer];
2、提供一个处理手势的方法,手势发生时或发生后调用此方法,通常由视图提供此方法
手势的状态:
UIGestureRecognizerState state; // 当前手势状态,枚举类型,分别在连续手势和不连续手势中起作用
连续运动手势,比如拖动、捏合、旋转
UIGestureRecognizerStateBegan // 当前手指刚接触到屏幕
UIGestureRecognizerStateChanged // 当前手指位置发生改变
UIGestureRecognizerStateEnded // 当前手指离开屏幕
UIGestureRecognizerStateFailed // 收到了一个无法识别的连续运动手势
UIGestureRecognizerStateCancelled // 出现了异常导致手势中断
不连续手势,比如点击和滑动,
UIGestureRecognizerStateRecognized // 当前发生不连续手势
UIPanGestureRecognizer 拖动手势:
创建手势
UIPanGestureRecognizer *panGestureRecognizer =
[[UIPanGestureRecognizer alloc]initWithTarget:self
action:@selector(panView:)];
- (CGPoint)translationInView:(UIView *)view; // 返回从上次重置后的触摸移动距离,手指触摸到屏幕上时,触点重置
- (CGPoint)velocityInView:(UIView *)view; // 返回触摸移动速度
- (void)setTranslation:(CGPoint)translation inView:(UIView *)view; // 重置初始位置
示例,通过不断重置原点,获得较小的移动距离增量:
-(void)panView:(UIPanGestureRecognizer *)recognizer{
if (recognizer.state == UIGestureRecognizerStateChanged ||
recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint translation = [recognizer translationInView:self]; // 获得当前移动增量
// 用户代码
// 重置原点位置
self.origin = CGPointMake(self.origin.x + translation.x, self.origin.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self]; // 重设触点位置,将移动距离重置为0
}
}
UIPinchGestureRecognizer 捏合手势:
属性:
CGFloat scale; // 缩放比例,捏合手势刚开始时,是1.0,随着数值放大,依次为1.1、1.2、1.5、2.0
// 随着缩小,又变为 1.5、1.2、1.0、0.9、0.8、0.7、0.6
CGFloat velocity; // 比例系数的变化速度,每秒钟变化多少
UIRotationGestureRecognizer 旋转手势:
属性:
CGFloat rotation; // 旋转的弧度
CGFloat velocity; // 比例系数的变化速度,每秒钟变化的弧度
属性:
NSUInteger numberOfTouchesRequired; // 参与滑动的手指数量,默认为1
UISwipeGestureRecognizerDirection direction; // 方向,包括从左到右、从上到下,或相反
当发生滑动手势时,相应方法只触发一次,并产生手势状态
UIGestureRecognizerStateRecognized
UITapGestureRecognizer 点击手势:
属性:
NSUInteger numberOfTapsRequired; // 点击的次数,默认为1
NSUInteger numberOfTouchesRequired; // 参与点击的手指数量,默认为1