iPhone手势处理--UIGestureRecognizer

来源:互联网 发布:stm32用串口4发送数据 编辑:程序博客网 时间:2024/05/16 12:38

一、概述

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是一个抽象类,我们主要是使用它的子类:

  • UITapGestureRecognizer

  • UIPinchGestureRecognizer

  • UIRotationGestureRecognizer

  • UISwipeGestureRecognizer

  • UIPanGestureRecognizer

  • UILongPressGestureRecognizer

从名字上我们就能知道, 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:selfaction:@selector(handleSingleTapFrom)];
    singleTapRecognizer.numberOfTapsRequired = 1; // 单击
    [self.view addGestureRecognizer:singleRecognizer];
    
    // 双击的 Recognizer
    UITapGestureRecognizer* double;
    doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@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.csdn.net/pjk1129/article/details/6824810




原创粉丝点击