事件處理方法
UIResponder中定義了一系列對事件的處理方法,他們分別是:
- –(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
- –(void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event
- –(void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event
- –(void)touchesCancelled:(NSSet )touches withEvent:(UIEvent )event
從方法名字可以知道,他們分別對應了屏幕事件的開始、移動、結束和取消幾個階段,前三個階段理解都沒問題,最后一個取消事件的觸發時機是在諸如突然來電話或是系統殺進程時調用。這些方法的第一個參數定義了UITouch對象的一個集合(NSSet),它的數量表示了這次事件是幾個手指的操作,目前iOS設備支持的多點操作手指數最多是5。第二個參數是當前的UIEvent對象。下圖展示了一個UIEvent對象與多個UITouch對象之間的關系。

一、點擊事件
首先,新建一個自定義的View繼承於UIView,並實現上述提到的事件處理方法,我們可以通過判斷UITouch的tapCount屬性來決定響應單擊、雙擊或是多次點擊事件。
MyView.m
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#import "MyView.h" @implementation MyView -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *aTouch in touches) { if (aTouch.tapCount == 2) { // 處理雙擊事件 [self respondToDoubleTapGesture]; } } } -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { } -(void)respondToDoubleTapGesture { NSLog(@"respondToDoubleTapGesture"); } @end |
二、滑動事件
滑動事件一般包括上下滑動和左右滑動,判斷是否是一次成功的滑動事件需要考慮一些問題,比如大部分情況下,用戶進行一次滑動操作,這次滑動是否是在一條直線上?或者是否是基本能保持一條直線的滑動軌跡。或者判斷是上下滑動還是左右滑動等。另外,滑動手勢一般有一個起點和一個終點,期間是在屏幕上畫出的一個軌跡,所以需要對這兩個點進行判斷。我們修改上述的MyView.m的代碼來實現一次左右滑動的事件響應操作。
MyView.m
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
#import "MyView.h" #define HORIZ_SWIPE_DRAG_MIN 12 //水平滑動最小間距 #define VERT_SWIPE_DRAG_MAX 4 //垂直方向最大偏移量 @implementation MyView -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *aTouch = [touches anyObject]; // startTouchPosition是一個CGPoint類型的屬性,用來存儲當前touch事件的位置 self.startTouchPosition = [aTouch locationInView:self]; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *aTouch = [touches anyObject]; CGPoint currentTouchPosition = [aTouch locationInView:self]; // 判斷水平滑動的距離是否達到了設置的最小距離,並且是否是在接近直線的路線上滑動(y軸偏移量) if (fabsf(self.startTouchPosition.x - currentTouchPosition.x) >= HORIZ_SWIPE_DRAG_MIN && fabsf(self.startTouchPosition.y - currentTouchPosition.y) <= VERT_SWIPE_DRAG_MAX) { // 滿足if條件則認為是一次成功的滑動事件,根據x坐標變化判斷是左滑還是右滑 if (self.startTouchPosition.x < currentTouchPosition.x) { [self rightSwipe];//右滑響應方法 } else { [self leftSwipe];//左滑響應方法 } //重置開始點坐標值 self.startTouchPosition = CGPointZero; } } -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { //當事件因某些原因取消時,重置開始點坐標值 self.startTouchPosition = CGPointZero; } -(void)
|