iPhone手势处理--UIGestureRecognizer

本文详细介绍iOS中使用UIGestureRecognizer进行手势识别的方法,包括Tap、Pinch、Rotation等常见手势的实现,并提供实例代码说明如何区分单击与双击等复杂手势场景。

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

一、概述

iPhone中处理触摸屏的操作,在3.2之前是主要使用的如下4种方式:

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

但是这种方式比较麻烦,目前有了比较简便的方式,就是使用UIGestureRecognizer。

二、UIGestureRecognizer

UIGestureRecognizer是一个抽象类,我们主要是使用它的子类:

从名字上我们就能知道, Tap(点一下)、Pinch(二指往內或往外拨动)、Rotation(旋转)、Swipe(滑动,快速移动)、Pan (拖移,慢速移动)以及 LongPress(长按)。举个例子,可以在viewDidLoad函数里面添加:

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
[self.view addGestureRecognizer:panRecognizer];

panRecognizer.maximumNumberOfTouches = 1;
panRecognizer.delegate = self;
[panRecognizer release];

其它手势方法类似。主要就是设置delegate和在需要的view上使用addGestureRecognizer。当然在要记得在作为delegate的view的头文件加上<UIGestureRecognizerDelegate>。

不过有些手势是关联的,怎么办呢?例如 Tap 与 LongPress、Swipe与 Pan,或是 Tap 一次与Tap 兩次。比如单击和双击,如果它识别出一种手势,其后的手势将不被识别,也就是说单击和双击并存时,它只能发送出单击的消息,这个时候就需要先判断是否时双击,在双击失效的情况下作为单击。

requireGestureRecognizerToFail,他可以指定某一个 recognizer,即便自己已经滿足條件了,也不會立刻触发,会等到该指定的 recognizer 确定失败之后才触发。

     
-  ( void ) viewDidLoad  {
     // 单击的 Recognizer
     UITapGestureRecognizer *  singleRecognizer ;
     singleRecognizer  =  [[ UITapGestureRecognizer  alloc ]  initWithTarget: self action: @selector ( handleSingleTapFrom )];
     singleTapRecognizer . numberOfTapsRequired  =  1 ;  // 单击
     [ self . view  addGestureRecognizer: singleRecognizer ];
    
     // 双击的 Recognizer
     UITapGestureRecognizer *  double ;
     doubleRecognizer  =  [[ UITapGestureRecognizer  alloc ]  initWithTarget: self action: @selector ( handleDoubleTapFrom )];
     doubleTapRecognizer . numberOfTapsRequired  =  2 ;  // 双击
     [ self . view  addGestureRecognizer: doubleRecognizer ];
    
     // 关键在这一行,如果双击确定偵測失败才會触发单击
     [singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];
     [ singleRecognizer  release ];
     [ doubleRecognizer  release ];
}
参考资料:
http://www.cocoachina.com/iphonedev/sdk/2010/1214/2471.html

http://blog.youkuaiyun.com/pjk1129/article/details/6824810




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值