UIGestureRecognizer iphone 手势识别(点击,捏合,旋转,拖拽,轻扫,长按)

本文详细介绍iOS中的各种手势识别器,包括点击、长按、捏合等,并提供代码示例,帮助开发者快速掌握手势识别技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UIGestureRecognizer是一个抽象类,定义了所有手势的基本行为,它有6个子类处理具体的手势:

1.UITapGestureRecognizer(任意手指任意次数的点击)

//点击次数

numberOfTapsRequired

//手指个数

numberOfTouchesRequired  

 


 

[plain]  viewplain copy
  1. UITapGestureRecognizer *tapGestureRecognizer [[UITapGestureRecognizer alloc] init];  
  2. [tapGestureRecognizer addTarget:self action:@selector(gestureRecognizerHandle:)];  
  3. [tapGestureRecognizer setNumberOfTapsRequired:2];  
  4. [tapGestureRecognizer setNumberOfTouchesRequired:2];  
  5. [self.view addGestureRecognizer:tapGestureRecognizer];  
  6. [tapGestureRecognizer release];  

 


2.UIPinchGestureRecognizer(两个手指捏合动作)

 

// 手指捏合,大于1表示两个手指之间的距离变大,小于1表示两个手指之间的距离变小

scale

// 手指捏合动作时的速率(加速度)

velocity


 

[plain]  viewplain copy
  1. UIPinchGestureRecognizer *pinchGestureRecognizer [[UIPinchGestureRecognizer alloc] init];  
  2. [pinchGestureRecognizer addTarget:self action:@selector(gestureRecognizerHandle:)];  
  3. [self.view addGestureRecognizer:pinchGestureRecognizer];  
  4. [pinchGestureRecognizer release];  

 

3.UIPanGestureRecognizer(摇动或者拖拽)

 

 

// 最少手指个数

minimumNumberOfTouches

//最多手指个数

maximumNumberOfTouches


 

[plain]  viewplain copy
  1. UIPanGestureRecognizer *panGestureRecognizer [[UIPanGestureRecognizer alloc] init];  
  2. [panGestureRecognizer addTarget:self action:@selector(gestureRecognizerHandle:)];  
  3. [panGestureRecognizer setMinimumNumberOfTouches:1];  
  4. [panGestureRecognizer setMaximumNumberOfTouches:5];  
  5. [self.view addGestureRecognizer:panGestureRecognizer];  
  6. [panGestureRecognizer release];  

 

4.UISwipeGestureRecognizer(手指在屏幕上滑动操作手势)

 

// 滑动手指的个数

numberOfTouchesRequired

// 手指滑动的方向 (Up,Down,Left,Right)

direction


[plain]  viewplain copy
  1. UISwipeGestureRecognizer *swipeGestureRecognizer [[UISwipeGestureRecognizer alloc] init];  
  2. [swipeGestureRecognizer addTarget:self action:@selector(gestureRecognizerHandle:)];  
  3. [swipeGestureRecognizer setNumberOfTouchesRequired:2];  
  4. [swipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionRight];  
  5. [self.view addGestureRecognizer:swipeGestureRecognizer];  
  6. [swipeGestureRecognizer release];  

5.UIRotationGestureRecognizer(手指在屏幕上旋转操作)

 

// 旋转方向,小于0为逆时针旋转手势,大于0为顺时针手势

rotation

// 旋转速率

velocity


 

[plain]  viewplain copy
  1. UIRotationGestureRecognizer *rotationGestureRecognize[[UIRotationGestureRecognizer alloc] init];  
  2. [rotationGestureRecognizeaddTarget:self action:@selector(gestureRecognizerHandle:)];  
  3. [self.view addGestureRecognizer:rotationGestureRecognizer];  
  4. [rotationGestureRecognizerelease];  

 

6.UILongPressGestureRecognizer(长按手势)

 

 

// Default is 0. The number of full taps requiredbefore the press for gesture to be recognized

numberOfTapsRequired

// 需要长按的手指的个数

numberOfTouchesRequired

// 需要长按的时间,最小为0.5s

minimumPressDuration

// 手指按住允许移动的距离

allowableMovement


 

[plain]  viewplain copy
  1. UILongPressGestureRecognizer *longPressGestureRecognizer [[UILongPressGestureRecognizer alloc] init];  
  2. [longPressGestureRecognizer addTarget:self action:@selector(gestureRecognizerHandle:)];  
  3. [longPressGestureRecognizer setMinimumPressDuration:1.0f];  
  4. [longPressGestureRecognizer setAllowableMovement:50.0];  
  5. [self.view addGestureRecognizer:longPressGestureRecognizer];  
  6. [longPressGestureRecognizer release];  



tap是指轻触手势。类似鼠标操作的点击。从iOS3.2版本开始支持完善的手势api:

   tap:轻触
   long press:在一点上长按
   pinch:两个指头捏或者放的操作
   pan:手指的拖动
   swipe:手指在屏幕上很快的滑动
   rotation:手指反向操作


这为开发者编写手势识别操作,提供了很大的方便,想想之前用android写手势滑动的代码(编写android简单的手势切换视图示例),尤其感到幸福。

这里写一个简单的tap操作。在下面视图的蓝色视图内增加对tap的识别:

image

 

当用手指tap蓝色视图的时候,打印日志输出:

image

代码很简单,首先要声明tap的recognizer:

   UITapGestureRecognizer*recognizer=[[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleTapFrom:)];
   [infoViewaddGestureRecognizer:recognizer];
   [recognizer release];


在这里:

  initWithTarget:self,要引用到Controller,因为一般这部分代码写在controller中,用self;
  action:@selector(handleTapFrom:),赋值一个方法名,用于当手势事件发生后的回调;
   [infoViewaddGestureRecognizer:recognizer],为view注册这个手势识别对象,这样当手指在该视图区域内,可引发手势,之外则不会引发


对应的回调方法:

   -(void)handleTapFrom:(UITapGestureRecognizer*)recognizer{
      NSLog(@">>>tapit");
   }


controller相关方法完整的代码(包含了一些与本文无关的视图构建代码):

   // Implement loadView to create a view hierarchyprogrammatically, without using a nib.
   - (void)loadView {
      //去掉最顶端的状态拦
      [[UIApplication sharedApplication] setStatusBarHidden:YESwithAnimation: UIStatusBarAnimationSlide];
     
       UIImage*image=[UIImage imageNamed:@"3.jpg"];
     
      //创建背景视图
      self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame]];
      UIImageView *backgroudView=[[UIImageView alloc]initWithImage:image];
       [self.viewaddSubview:backgroudView];
     
     
     
       UIView*bottomView=[[UIView alloc] initWithFrame:CGRectMake(0, 1024-70, 768,70)];
      bottomView.backgroundColor=[UIColor grayColor];
      bottomView.alpha=0.8;
     
       //UIButton*backButton=[[UIButton alloc] initWithFrame:CGRectMake(10, 10, 100,40)];
       UIButton*backButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
      [backButton setTitle:@"ok"forState:UIControlStateNormal];
      backButton.frame=CGRectMake(10, 15, 100, 40);
     
      [bottomView addSubview:backButton];
     
       [self.viewaddSubview:bottomView];
     
       UIView*infoView=[[UIView alloc] initWithFrame:CGRectMake(200, 700,768-400, 70)];
      infoView.backgroundColor=[UIColor blueColor];
      infoView.alpha=0.6;
      infoView.layer.cornerRadius=6;
      infoView.layer.masksToBounds=YES;
       [self.viewaddSubview:infoView];
     
      UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc]initWithTarget:selfaction:@selector(handleTapFrom:)];
       [infoViewaddGestureRecognizer:recognizer];
      [recognizer release];
   }


   -(void)handleTapFrom:(UITapGestureRecognizer*)recognizer{
      NSLog(@">>>tapit");
   }


    

    

    

    

   翻页效果,类似下面的样子:

   imageimage

   在电子书应用中会很常见。这里需要两个要点:

      翻页动画
      手势上下轻扫(swipe)的处理


    

  先说一下轻扫(swipe)的实现,可以参考编写简单的手势示例:Tap了解手势种类。

  在viewDidLoad方法中注册了对上、下、左、右四个方向轻松的处理方法:

       -(void)viewDidLoad {
         
          UISwipeGestureRecognizer*recognizer;
         
          recognizer =[[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom:)];
          [recognizersetDirection:(UISwipeGestureRecognizerDirectionRight)];
          [[self view]addGestureRecognizer:recognizer];
          [recognizerrelease];
         
          recognizer =[[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom:)];
          [recognizersetDirection:(UISwipeGestureRecognizerDirectionUp)];
          [[self view]addGestureRecognizer:recognizer];
          [recognizerrelease];
         
          recognizer =[[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom:)];
          [recognizersetDirection:(UISwipeGestureRecognizerDirectionDown)];
          [[self view]addGestureRecognizer:recognizer];
          [recognizerrelease];
         
          recognizer =[[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom:)];
          [recognizersetDirection:(UISwipeGestureRecognizerDirectionLeft)];
          [[self view]addGestureRecognizer:recognizer];
          [recognizerrelease];
         
         
          [superviewDidLoad];


       

   可以看到,都是同一个方法,handleSwipeFrom。

  在该方法中,再识别具体是哪个方向的轻扫手势,比如判断是向下的轻扫:

      -(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
          NSLog(@"Swipereceived.");
         
          if(recognizer.direction==UISwipeGestureRecognizerDirectionDown){
             NSLog(@"swipe down");


   判断是向上的轻扫:

       if(recognizer.direction==UISwipeGestureRecognizerDirectionUp){
          NSLog(@"swipeup");


   有关动画的处理,比如向下(往回)翻页,类似这样:

       [UIViewbeginAnimations:@"animationID" context:nil];
       [UIViewsetAnimationDuration:0.7f];
       [UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];
       [UIViewsetAnimationRepeatAutoreverses:NO];
       [UIViewsetAnimationTransition:UIViewAnimationTransitionCurlDownforView:self.view cache:YES];


      [currentView removeFromSuperview];
       [self.viewaddSubview:contentView];


       [UIViewcommitAnimations];

   向上(向前)翻页,只需改为:

       [UIViewbeginAnimations:@"animationID" context:nil];
       [UIViewsetAnimationDuration:0.7f];
       [UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];
       [UIViewsetAnimationRepeatAutoreverses:NO];
       [UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUpforView:self.view cache:YES];


      [currentView removeFromSuperview];
       [self.viewaddSubview:contentView];


       [UIViewcommitAnimations];

  如果是电子书,还需要考虑一个问题,就是有多个页面(图形),比如50页。那么需要有一个数据结构来保存这些页面的图片路径:

      objc数据结构,比如数组
      sqlite数据库表


   这样,写一套翻页代码和加载什么图形之间就可以解耦。

   本文示例使用的是数组,类似这样:

      pages=[[NSArray alloc]initWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg",@"6.jpg",
                    nil];


   图片保存在resources下。

   为了能让上页下页翻页的时候找到关联的页面,采用了如下机制:

      将图片封装为UIImageView显示
      可以为UIImageView设置一个tag值,值为数组下标+1
      这样,上级view有方法能根据tag查询到UIImageView,比如:UIView *currentView=[self.viewviewWithTag:currentTag];
      设置一个成员变量currentTag保存当前的tag值


   比如这样,当应用加载的时候显示第一页:

         currentTag=1;
         
          NSString *path = [[NSBundlemainBundle] pathForResource:@"pageflip1"ofType:@"mp3"];
          player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL];
         
          //[[UIApplicationsharedApplication] setStatusBarHidden:YESanimated:NO];
          [[UIApplicationsharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
          UIImageView *contentView =[[UIImageView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame]]; 
          [contentViewsetImage:[UIImage imageNamed:[pagesobjectAtIndex:(currentTag-1)]]]; 
          [contentViewsetUserInteractionEnabled:YES];
         contentView.tag=currentTag;


   在翻页时的处理:

       if(currentTag<[pages count]) {
          UIView*currentView=[self.view viewWithTag:currentTag];
         currentTag++;
         
          UIImageView *contentView =[[UIImageView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame]];
          [contentViewsetImage:[UIImage imageNamed:[pagesobjectAtIndex:(currentTag-1)]]]; 
          [contentViewsetUserInteractionEnabled:YES];
         contentView.tag=currentTag;
         
          [UIViewbeginAnimations:@"animationID" context:nil];
          [UIViewsetAnimationDuration:0.7f];
          [UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];
          [UIViewsetAnimationRepeatAutoreverses:NO];
          [UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUpforView:self.view cache:YES];
         
          [currentViewremoveFromSuperview];
          [self.viewaddSubview:contentView];
         
          [UIViewcommitAnimations];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值