手势识别(一)

1、UIGestureRecognizer介绍

手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性。
iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了UIGestureRecognizer类。手势识别UIGestureRecognizer类是个抽象类,下面的子类是具体的手势,开发这可以直接使用这些手势识别。
  • Tap(点一下)
  • Pinch(二指往內或往外拨动,平时经常用到的缩放)
  • Rotation(旋转)
  • Swipe(滑动,快速移动)
  • Pan (拖移,慢速移动)
  •  LongPress(长按)
UIGestureRecognizer的继承关系如下:
 
 

2、使用手势的步骤

使用手势很简单,分为两步:
  1. 创建手势实例。当创建手势时,指定一个回调方法,当手势开始,改变、或结束时,回调方法被调用。
  2. 添加到需要识别的View中。每个手势只对应一个View,当屏幕触摸在View的边界内时,如果手势和预定的一样,那就会回调方法。
ps:一个手势只能对应一个View,但是一个View可以有多个手势。
建议在真机上运行这些手势,模拟器操作不太方便,可能导致你认为手势失效。

3、Pan 拖动手势:

1 UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];  
2 snakeImageView.frame = CGRectMake(50, 50, 100, 160);  
3 UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]  
4                                                 initWithTarget:self  
5                                                 action:@selector(handlePan:)];      
6 [snakeImageView addGestureRecognizer:panGestureRecognizer];  
7 [self.view setBackgroundColor:[UIColor whiteColor]];  
8 [self.view addSubview:snakeImageView];  

 

 
新建一个ImageView,然后添加手势
回调方法:
1 - (void) handlePan:(UIPanGestureRecognizer*) recognizer  
2 {  
3     CGPoint translation = [recognizer translationInView:self.view];  
4     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,  
5                                    recognizer.view.center.y + translation.y);  
6     [recognizer setTranslation:CGPointZero inView:self.view];  
7       
8 }  

 

4、Pinch缩放手势

1 UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]
1 - (void) handlePinch:(UIPinchGestureRecognizer*) recognizer  
2 {  
3     recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);  
4     recognizer.scale = 1;  
5 }  

 

 

5、Rotation旋转手势

1  UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(handleRotate:)];  
2  [snakeImageView addGestureRecognizer:rotateRecognizer];  

 

1 - (void) handleRotate:(UIRotationGestureRecognizer*) recognizer  
2 {  
3     recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);  
4     recognizer.rotation = 0;  
5 }  

 

 
 
posted @ 2016-01-05 18:52  Mantis-man  阅读(204)  评论(0编辑  收藏  举报