在 iOS 的开发过程中,我们一般使用 touches 方法来监听 view 的触摸事件,但是这样使用会有一些弊端:
- 必须得自定义 view, 在自定义的 View 当中去实现 touches 方法
- 由于是在 view 内部的 touches 方法中监听触摸事件,因此默认情况下,无法让其他外界对象监听 view 的触摸事件
- 不容易区分用户具体的手势行为
鉴于这些问题,在iOS 3.2 之后,苹果推出了手势识别功能(Gesture Recognizer)在触摸事件处理方面大大简化了开发者的开发难度。
UIGestureRecognizer 手势识别器
- 利用 UIGestureRecognizer,能轻松识别用户在某个 view 上面做的一些常见手势
- UIGestureRecognizer 是一个抽象类,定义了所有手势的基本行为,使用它的子类才能处理具体的手势
- 点按手势
UITapGestureRecognizer
- 长按手势
UILongPressGestureRecognizer
- 平移(拖拽)手势
UIPanGestureRecognizer
- 轻扫手势
UISwipeGestureRecognizer
- 旋转手势
UIRotationGestureRecognizer
- 捏合手势
UIPinchGestureRecognizer
- 点按手势
- 手势的使用方法
- 创建手势
- 添加手势
- 实现手势方法
- 补充(手势也可以设置代理)
1. UITapGestureRecognizer 点按手势
点按手势效果图
1 2 3 4 5 6 7 8 9 10 11 12 |
- (void)topGes { //创建点按手势 UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]; //手势也可以设置代理 tapGes.delegate = self; //添加手势 [self.imageView addGestureRecognizer:tapGes]; } - (void)tap { NSLog(@"现在是点按手势"); } |
- 实现代理方法
1 2 3 4 5 6 7 8 9 10 11 |
//代理方法:是否允许接收手指 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { //让图片左边可以点击,右边不能点击 //获取当前手指所在的点进行判断 CGPoint curP = [touch locationInView:self.imageView]; if (curP.x > self.imageView.bounds.size.width * 0.5) { return NO; }else { return YES; } } |
2. UILongPressGestureRecognizer 长按手势
长按手势效果图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
- (void)longPGes { UILongPressGestureRecognizer *longPGes = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longP:)]; [self.imageView addGestureRecognizer:longPGes]; } //当长按并移动时,会多次调用这个方法 - (void)longP:(UILongPressGestureRecognizer *)longP { //判断长按时的状态 if (longP.state == UIGestureRecognizerStateBegan) { NSLog(@"开始长按"); }else if (longP.state == UIGestureRecognizerStateChanged) { NSLog(@"- - - 长按时手指移动了 - - -"); }else if (longP.state == UIGestureRecognizerStateEnded) { NSLog(@"长按结束"); } } |
3. UIPanGestureRecognizer 平移(拖拽)手势
平移(拖拽)手势效果图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
- (void)panGes { UIPanGestureRecognizer *panGes = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [self.imageView addGestureRecognizer:panGes]; } - (void)pan:(UIPanGestureRecognizer *)pan { //获取偏移量 CGPoint transP -h"> { //获取偏移量 CGPoint transP
鉴于这些问题,在iOS 3.2 之后,苹果推出了手势识别功能(Gesture Recognizer)在触摸事件处理方面大大简化了开发者的开发难度。 UIGestureRecognizer 手势识别器
1. UITapGestureRecognizer 点按手势点按手势效果图
2. UILongPressGestureRecognizer 长按手势长按手势效果图
3. UIPanGestureRecognizer 平移(拖拽)手势平移(拖拽)手势效果图
|