在 iOS 平台上,使用者與 App 的每一次互動,幾乎都離不開「事件」這兩個字。從最簡單的點擊、滑動,到搖一搖手機、耳機線控,背後都是一套完整的事件處理機制在支撐。本文將帶你系統性地梳理 iOS 的輸入事件體系,並深入觸摸事件與手勢識別的實作細節。
iOS 的輸入事件大致可以分為三大類:
在程式碼層面,iOS 所有的輸入事件都是 UIEvent 類的實例。該類透過列舉型別定義了事件的分類:
typedef NS_ENUM(NSInteger, UIEventType){
UIEventTypeTouches,
UIEventTypeMotion,
UIEventRemoteControl,
};
需要注意的是,能夠處理觸摸事件的物件,必須繼承自 UIResponder。
UIView 是 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下面這段範例展示了如何透過移動量,讓一個視圖跟著手指走:
#pragma mark - UITouch 事件
// 觸摸開始
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"觸摸開始");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
// 觸摸移動
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"觸摸移動 Touch 物件個數:%d", [touches count]);
// 1. 取得當前手指的位置
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
// 2. 取得上一次手指的位置
CGPoint preLocation = [touch previousLocationInView:self.view];
// 3. 計算兩次位置之間的偏移
CGPoint offset = CGPointMake(location.x - preLocation.x, location.y - preLocation.y);
// 4. 用偏移量調整視圖位置
[_demoView setCenter:CGPointMake(_demoView.center.x + offset.x, _demoView.center.y + offset.y)];
NSLog(@"觸摸移動");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
// 觸摸結束
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"觸摸完成");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
// 觸摸中斷
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"觸摸中斷");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
當 hit-test 視圖無法處理某個事件時,事件會沿著響應者鏈一路向上傳遞:
UIApplication。UIApplication 也無法處理,事件最終被丟棄。當使用者點擊螢幕時,系統會產生一個 UITouch 物件交給 UIApplication,再由 window 透過 hitTest、pointInside 找出最適合回應的視圖。找到之後,觸摸方法就由該視圖負責,上級視圖不再介入。
如果希望某個視圖完全不響應觸摸,可以:
userInteractionEnabled = NO;hidden = YES;alpha 介於 0~0.01 之間。UITapGestureRecognizer(點按)UIPinchGestureRecognizer(捏合)UIPanGestureRecognizer(拖動)UISwipeGestureRecognizer(輕掃)UIRotationGestureRecognizer(旋轉)UILongPressGestureRecognizer(長按)通常會在視圖載入時定義手勢(UIGestureRecognizer 是抽象類,必須具現化後使用):
// 尚未發生觸摸,所有手勢的預設狀態
UIGestureRecognizerStatePossible,
// 手勢已開始,但尚未改變或完成
UIGestureRecognizerStateBegan,
// 手勢狀態改變
UIGestureRecognizerStateChanged,
// 手勢完成
UIGestureRecognizerStateEnded,
// 手勢取消,恢復為 Possible
UIGestureRecognizerStateCancelled,
// 手勢失敗,恢復為 Possible
UIGestureRecognizerStateFailed,
// 成功識別到手勢
UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
手勢識別的常用屬性包括 state(手勢狀態)與 view(手勢發生的視圖);常用方法則有 locationInView,用來取得手勢在對應視圖中的位置。
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 點按手勢
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
[tap setNumberOfTapsRequired:1]; // 點按次數
[tap setNumberOfTouchesRequired:1]; // 點按手指數量
[self.demoView addGestureRecognizer:tap];
// 2. 捏合手勢
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
[self.demoView addGestureRecognizer:pinch];
// 3. 旋轉手勢
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationAction:)];
[self.demoView addGestureRecognizer:rotation];
// 4. 拖放手勢
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[self.demoView addGestureRecognizer:pan];
// 5. 長按手勢
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
[self.demoView addGestureRecognizer:longPress];
// 6. 輕掃手勢(需指定方向,否則預設只接收向右)
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.view addGestureRecognizer:swipeLeft];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
[self.view addGestureRecognizer:swipeRight];
UISwipeGestureRecognizer *swipeTop = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
[swipeTop setDirection:UISwipeGestureRecognizerDirectionUp];
[self.view addGestureRecognizer:swipeTop];
UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
[swipeDown setDirection:UISwipeGestureRecognizerDirectionDown];
[self.view addGestureRecognizer:swipeDown];
}
// 輕掃手勢
- (void)swipeAction:(UISwipeGestureRecognizer *)sender {
switch (sender.direction) {
case UISwipeGestureRecognizerDirectionLeft: NSLog(@"向左掃"); break;
case UISwipeGestureRecognizerDirectionRight: NSLog(@"向右掃"); break;
case UISwipeGestureRecognizerDirectionUp: NSLog(@"向上掃"); break;
case UISwipeGestureRecognizerDirectionDown: NSLog(@"向下掃"); break;
default: break;
}
}
// 長按手勢:利用 tag 在放大與縮小之間切換
- (void)longPressAction:(UILongPressGestureRecognizer *)sender {
CGFloat scale;
if (_demoView.tag == 0) {
scale = 2.0;
_demoView.tag = 1;
} else {
scale = 0.5;
_demoView.tag = 0;
}
sender.view.transform = CGAffineTransformScale(sender.view.transform, scale, scale);
}
// 拖放手勢:需判斷手指狀態
- (void)panAction:(UIPanGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateChanged) {
[_demoView setCenter:[sender locationInView:self.view]];
} else if (sender.state == UIGestureRecognizerStateEnded) {
[_demoView setBackgroundColor:[UIColor yellowColor]];
}
}
// 旋轉手勢
- (void)rotationAction:(UIRotationGestureRecognizer *)sender {
sender.view.transform = CGAffineTransformRotate(sender.view.transform, sender.rotation);
sender.rotation = 0.0f; // 旋轉角度需復位
}
// 捏合手勢
- (void)pinchAction:(UIPinchGestureRecognizer *)sender {
sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale);
sender.scale = 1.0f; // 縮放比例需復位
NSLog(@"捏我了");
}
// 點按手勢
- (void)tapAction:(UITapGestureRecognizer *)sender {
// 開發時,若非必要,盡量不要對同一個 UI 控件同時使用觸摸與手勢
NSLog(@"點我了 %@", sender);
}
要讓畫面回應搖晃手勢,可以自訂一個搖晃監聽視圖 ShakeListenerView,並讓它回傳 YES 以成為第一響應者:
- (BOOL)canBecomeFirstResponder {
return YES;
}
接著在 Storyboard 中把 ViewController 的 View 類別設為 ShakeListenerView,並在 ViewController 中補上三個關鍵方法:
#pragma mark - 讓 ViewController 支援搖晃的三個方法
// 1. 視圖出現時成為第一響應者
- (void)viewDidAppear:(BOOL)animated {
[self.view becomeFirstResponder];
[super viewDidAppear:animated];
}
// 2. 視圖關閉時註銷第一響應者
- (void)viewDidDisappear:(BOOL)animated {
[self.view resignFirstResponder];
[super viewDidDisappear:animated];
}
// 3. 監聽並判斷是否搖晃了手機
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
NSLog(@"搖啊搖,搖到外婆橋!!!");
}
}
掌握觸摸事件與手勢識別這兩塊基礎,你就能為 App 打造自然流暢的互動體驗。接下來不妨動手做個小實驗,把點按、拖動、旋轉都套在同一個視圖上,親身感受事件在響應者鏈中流轉的過程。