iOS手勢


      在iPhone中,我們除了用touchesBegan、touchesMoved、touchesEnded、touchesCancelled這組方法來控制使用者的手指觸控外,也可以用UIGestureRecognizer 的衍生類別來進行判斷,該類別的好處是有自己現成的手勢,開發者可以自己計算手指移動的軌跡。

 1、首先看下touchesBegan、touchesMoved、touchesEnded、touchesCancelled者四個方法的使用。

    touchesBegan:是用戶第一次接觸屏幕時響應的方法。

    - (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event{

         NSUInteger numType = [[touches anyObject] tapCount];

         NSUInteger numTouches = [touches count];

    }

    touchesMoved:是用戶手指移過屏幕時響應的方法。這里可以得到當前手指的位置以及原來的位置等信息。

    touchesEnded:用戶手指離開屏幕時響應的方法。

    touchesCancelled:當發生某些事件導致手勢中斷時響應的方法,要說明的是調用了該方法就不會響應touchesEned方法了。

2、現在了解下UIGestureRecognizer的使用

    UIGestureRecognizer衍生類別有:UITapGestureRecognizer、UIPinchGestureRecognizer、UIRotationGestureRecognizer、UISwipeGestureRecognizer、UIPanGEstureRecognizer、UiLongPressGestureRecognizer,他們所代表的手勢分別是Tap(點一下)、Pinch(二指往外或往內撥動)、Rotation(旋轉)、Swipe(滑動、快速移動)、Pan(拖移、慢速移動)、LongPress(長時間按)。

    - (void)viewDidLoad {     

    UISwipeGestureRecognizer* recognizer;      

    // handleSwipeFrom 是偵測到手勢,所要響應的方法     

     recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom)];      

    // 不同的 Recognizer 有不同的實體變數      

    // 例如 SwipeGesture 可以指定方向      

    // 而 TapGesture 則可以指定次數     

    recognizer.direction = UISwipeGestureRecognizerDirectionUp     

    [self.view addGestureRecognizer:recognizer];     

    [recognizer release];  

   }      

  - (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {     

     // 觸發手勢事件后,在這里作些事情      

      // 底下是刪除手勢的方法     

     [self.view removeGestureRecognizer:recognizer];

    }  

      但是這里有個問題,Tap和LongPress,一個是點擊一次一個長按,所以當我們點擊屏幕的時候,我們怎么分清這是點擊還是准備長按呢?Swipe和Pan也有這樣的問題,只要手指一移動就會出發Pan,這樣的話永遠不會出發Swipe,這個問題要出現的前提是同時注冊了這些手勢。

     所以需要一個解決方法:幸好UIGestureRecognizer類提供了一個方法requireGestureRecognizerToFail它可以指定某一個recognizer,即便自己滿足條件; 也不會立即執行會等到指定的recognizer確定失敗之后才觸發。

  - (void)viewDidLoad {     

    // 單擊的 Recognizer     

    UITapGestureRecognizer* singleRecognizer;  

    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSingleTapFrom)];

        singleTapRecognizer.numberOfTapsRequired = 1; 

    // 單擊   

     [self.view addGestureRecognizer:singleRecognizer];   

    // 雙擊的 Recognizer     

    UITapGestureRecognizer* doubleRecognizer;  

    doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleDoubleTapFrom)];

        doubleTapRecognizer.numberOfTapsRequired = 2;

    // 雙擊     

    [self.view addGestureRecognizer:doubleRecognizer];         

    // 關鍵在這一行,如果雙擊確定偵測失敗才會觸發單擊   

    [singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];   

    [singleRecognizer release];  

    [doubleRecognizer release];

    }  

   

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM