一、概述
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 確定失敗之後才觸發。
http://www.cocoachina.com/iphonedev/sdk/2010/1214/2471.html
http://blog.csdn.net/pjk1129/article/details/6824810