iPhone手势处理--UIGestureRecognizer
一、概述
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?{ // 單擊的 RecognizerUITapGestureRecognizer*?singleRecognizer;singleRecognizer?=?[[UITapGestureRecognizer?alloc]?initWithTarget:selfaction:@selector(handleSingleTapFrom)];singleTapRecognizer.numberOfTapsRequired?=?1;?// 單擊[self.view?addGestureRecognizer:singleRecognizer];// 雙擊的 RecognizerUITapGestureRecognizer*?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
 
 
 
總結
以上是生活随笔為你收集整理的iPhone手势处理--UIGestureRecognizer的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 视觉应用工程师 篇二
 - 下一篇: 如何接受上级指令_职场老手教你怎么应对领