iOS 觸摸事件概覽
iOS 中的事件大致可分為三大類:
響應者物件
在 iOS 中,並非任何物件都能處理事件,只有繼承自 UIResponder 的物件才能接收並處理,我們稱之為「響應者物件」。UIApplication、UIViewController、UIView 都繼承自 UIResponder,因此都是響應者物件。
UIResponder 內部提供了以下方法來處理事件。
觸摸事件(對應 Android 的 action_down、action_move、action_up、action_cancel):
- (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;
加速計事件(有點像 Android 的感測器):
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event; - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event; - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
遠程控制事件:
- (void)remoteControlReceivedWithEvent:(UIEvent *)event;
UIView 的觸摸事件處理
UIView 是 UIResponder 的子類,可以覆寫下列四個方法來處理不同的觸摸事件。
一根或多根手指開始觸摸 view 時,系統會自動呼叫:
- (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
手指在 view 上移動時(隨移動持續呼叫):
- (void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event
手指離開 view 時:
- (void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event
觸摸結束前被系統事件(例如來電)打斷時:
- (void)touchesCancelled:(NSSet )touches withEvent:(UIEvent )event
touches 中存放的都是 UITouch 物件。當使用者用一根手指觸摸螢幕時,系統會建立一個對應的 UITouch 物件,一根手指對應一個 UITouch。
UITouch 的作用
它保存著與手指相關的資訊,如觸摸位置、時間、階段。手指移動時系統會更新同一個 UITouch 物件,使其持續記錄觸摸位置;手指離開螢幕時,系統會銷毀對應的 UITouch 物件。
UITouch 的屬性
觸摸產生時所處的窗口 @property(nonatomic,readonly,retain) UIWindow *window; 觸摸產生時所處的視圖 @property(nonatomic,readonly,retain) UIView *view; 短時間內點按屏幕的次數,可以根據tapCount判斷單擊、雙擊或更多的點擊 @property(nonatomic,readonly) NSUInteger tapCount; 記錄了觸摸事件產生或變化時的時間,單位是秒 @property(nonatomic,readonly) NSTimeInterval timestamp; 當前觸摸事件所處的狀態 @property(nonatomic,readonly) UITouchPhase phase; - (CGPoint)locationInView:(UIView *)view; 返回值表示觸摸在view上的位置 這裡返回的位置是針對view的坐標系的(以view的左上角為原點(0, 0)) 調用時傳入的view參數為nil的話,返回的是觸摸點在UIWindow的位置 - (CGPoint)previousLocationInView:(UIView *)view; 該方法記錄了前一個觸摸點的位置
自訂控制項拖拽效果
iOS 做法:
1. 自訂 view 繼承自 UIView
2. 覆寫 touchesMoved 實作具體邏輯
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //取得UITouch對象 UITouch *touch = [touches anyObject]; //獲取上一個點 CGPoint p = [touch previousLocationInView:self]; //獲取當前點 CGPoint currp = [touch locationInView:self]; //產生平移拖拽效果 self.transform = CGAffineTransformTranslate(self.transform, currp.x - p.x, currp.y - p.y); }
對照 Android 做法:
1. 自訂 view 繼承自 View
2. 覆寫 onTouchEvent 實作具體邏輯
private int x, y; @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: x = (int) event.getRawX(); y = (int) event.getRawY(); break; case MotionEvent.ACTION_MOVE: int mx = (int)event.getRawX(); int my = (int)event.getRawY(); // setTranslationX(getTranslationX()+mx-x); // setTranslationY(getTranslationY()+my-y); layout(getLeft()+mx-x,getTop()+my-y,getLeft()+getMeasuredWidth()+mx-x,getTop()+getMeasuredHeight()+my-y); x = mx; y = my; break; } return true; }
UIGestureRecognizer
自 iOS 3.2 起,Apple 推出了手勢識別功能。有了 UIGestureRecognizer,就能輕鬆辨識使用者在 view 上做的常見手勢。
UIGestureRecognizer UIGestureRecognizer是一個抽象類,定義了所有手勢的基本行為,使用它的子類才能處理具體的手勢 UITapGestureRecognizer(敲擊) UIPinchGestureRecognizer(捏合,用於縮放) UIPanGestureRecognizer(拖拽) UISwipeGestureRecognizer(輕掃) UIRotationGestureRecognizer(旋轉) UILongPressGestureRecognizer(長按)
手勢識別器的用法相似,以 UITapGestureRecognizer 為例:
//創建手勢識別器對象 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init]; //設置手勢識別器對象的具體屬性 // 連續敲擊2次 tap.numberOfTapsRequired = 2; // 需要2根手指一起敲擊 tap.numberOfTouchesRequired = 2; //添加手勢識別器到對應的view上 [self.iconView addGestureRecognizer:tap]; 監聽手勢的觸發 [tap addTarget:self action:@selector(tapIconView:)];
上面的拖拽效果也能用手勢方式實作:
//頁面加載完成時調用 - (void)viewDidLoad { [super viewDidLoad]; //創建手勢識別器對象 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; //添加手勢識別器到對應的view上 [self.imageView addGestureRecognizer:pan]; } - (void)pan:(UIPanGestureRecognizer *)pan { // 獲取手勢的觸摸點 // CGPoint curP = [pan locationInView:self.imageView]; // 獲取手勢的移動,也是相對於最開始的位置 CGPoint transP = [pan translationInView:self.imageView]; self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, transP.x, transP.y); // 復位 [pan setTranslation:CGPointZero inView:self.imageView]; //判斷當前手指狀態 //if (pan.state == UIGestureRecognizerStateBegan) {//手指按下時類似於Android中的ACTION_DOWN //} }
其中 pan.state 對應 UIGestureRecognizerState 有如下狀態:
// 沒有觸摸事件發生,所有手勢識別的默認狀態 UIGestureRecognizerStatePossible, // 一個手勢已經開始但尚未改變或者完成時 UIGestureRecognizerStateBegan, // 手勢狀態改變 UIGestureRecognizerStateChanged, // 手勢完成 UIGestureRecognizerStateEnded, // 手勢取消,恢復至Possible狀態 UIGestureRecognizerStateCancelled, // 手勢失敗,恢復至Possible狀態 UIGestureRecognizerStateFailed, // 識別到手勢識別 UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
注意:預設不支援多個手勢同時作用(例如無法同時縮放與旋轉),若要支援需實作 UIGestureRecognizerDelegate 的 shouldRecognizeSimultaneouslyWithGestureRecognizer 方法:
#pragma mark - 手勢代理方法 // 是否允許開始觸發手勢 //- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer //{ // return NO; //} // 是否允許同時支持多個手勢,默認是不支持多個手勢 // 返回yes表示支持多個手勢 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } // 是否允許接收手指的觸摸點 //- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{ // // 獲取當前的觸摸點 // CGPoint curP = [touch locationInView:self.imageView]; // return YES; //}
事件傳遞
一個 view 為什麼不能處理事件:
userInteractionEnabled = NO、hidden = YES、alpha <= 0.01
此外 UIImageView 預設不允許使用者互動,因此其子控制項預設也無法接收事件。
系統會透過遞迴找出最合適的 view。第一個接收事件的是窗口,事件傳給窗口後,它會尋找最合適的 view:
1. 判斷自己能否接收事件
2. 判斷觸摸點是否在窗口上
3. 從後往前遍歷子控制項,把事件傳給子控制項
4. 子控制項再做同樣判斷,持續遞迴,直到找到最合適的 view
hitTest 與 pointInside 方法:
// 事件傳遞的時候調用 // 當事件傳遞給控件的時候,就會調用控件的這個方法,尋找最合適的view // point:當前的觸摸點,point這個點的坐標系就是方法調用者 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { // 調用系統的做法去尋找最合適的view,返回最合適的view UIView *fitView = [super hitTest:point withEvent:event]; // NSLog(@"fitView--%@",fitView); return fitView; } // 作用:判斷當前這個點在不在方法調用者(控件)上 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { return YES; }
hitTest 的底層實作:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { // 1.判斷當前控件能否接收事件 if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) return nil; // 2. 判斷點在不在當前控件 if ([self pointInside:point withEvent:event] == NO) return nil; // 3.從後往前遍歷自己的子控件 NSInteger count = self.subviews.count; for (NSInteger i = count - 1; i >= 0; i--) { UIView *childView = self.subviews[i]; // 把當前控件上的坐標系轉換成子控件上的坐標系 CGPoint childP = [self convertPoint:point toView:childView]; UIView *fitView = [childView hitTest:childP withEvent:event]; if (fitView) { // 尋找到最合適的view return fitView; } } // 循環結束,表示沒有比自己更合適的view return self; }
響應者鏈的事件傳遞
touch 的預設做法是:自己不處理,交給上一個響應者,而上一個響應者預設是父控制項:
以上就是觸摸事件與手勢處理的完整梳理,希望對大家有所幫助。