您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 開發入門:觸摸事件與手勢識別完全解析

編輯:iOS 相關資訊

在 iOS 平台上,使用者與 App 的每一次互動,幾乎都離不開「事件」這兩個字。從最簡單的點擊、滑動,到搖一搖手機、耳機線控,背後都是一套完整的事件處理機制在支撐。本文將帶你系統性地梳理 iOS 的輸入事件體系,並深入觸摸事件與手勢識別的實作細節。

一、iOS 的輸入事件有哪些

iOS 的輸入事件大致可以分為三大類:

  • 觸摸事件:例如點擊、滑動,是最直觀、最常見的互動方式。
  • 運動事件:例如搖一搖、手機傾斜、行走,這類事件由硬體感測器觸發,不需要人為去「畫」出來。
  • 遠程控制事件:例如透過耳機線控來調節音量或切歌。

在程式碼層面,iOS 所有的輸入事件都是 UIEvent 類的實例。該類透過列舉型別定義了事件的分類:

typedef NS_ENUM(NSInteger, UIEventType){
    UIEventTypeTouches,
    UIEventTypeMotion,
    UIEventRemoteControl,
};

需要注意的是,能夠處理觸摸事件的物件,必須繼承自 UIResponder。

二、觸摸事件的處理

1. UIView 的四個觸摸方法

UIView 是 UIResponder 的子類,它提供了四個方法來回應不同階段的觸摸:

  1. 一根或多根手指開始觸摸螢幕:- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  2. 手指在螢幕上移動(移動過程中會持續觸發):- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  3. 手指離開螢幕:- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  4. 觸摸被系統事件(如來電)打斷:- (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);
    }
}

2. 響應者鏈(Responder Chain)

當 hit-test 視圖無法處理某個事件時,事件會沿著響應者鏈一路向上傳遞:

  1. 若 hit-test 視圖有對應的控制器,先傳給控制器;若沒有,則傳給它的父視圖。
  2. 如果視圖或其控制器無法處理,就繼續往父視圖傳遞。
  3. 視圖繼承樹中每一層上級視圖若都無法處理,就重複上述步驟。
  4. 直到最上層視圖仍無法處理,事件會傳給 window 物件。
  5. window 無法處理,則傳給 UIApplication。
  6. 若 UIApplication 也無法處理,事件最終被丟棄。

當使用者點擊螢幕時,系統會產生一個 UITouch 物件交給 UIApplication,再由 window 透過 hitTest、pointInside 找出最適合回應的視圖。找到之後,觸摸方法就由該視圖負責,上級視圖不再介入。

3. 三種「不接受事件」的方法

如果希望某個視圖完全不響應觸摸,可以:

  • 關閉使用者互動:userInteractionEnabled = NO;
  • 隱藏視圖:hidden = YES;
  • 設定透明度:alpha 介於 0~0.01 之間。

三、手勢識別

1. iOS 支援的六種手勢

  • UITapGestureRecognizer(點按)
  • UIPinchGestureRecognizer(捏合)
  • UIPanGestureRecognizer(拖動)
  • UISwipeGestureRecognizer(輕掃)
  • UIRotationGestureRecognizer(旋轉)
  • UILongPressGestureRecognizer(長按)

2. 使用手勢的四個步驟

通常會在視圖載入時定義手勢(UIGestureRecognizer 是抽象類,必須具現化後使用):

  1. 建立手勢識別實例。
  2. 設定手勢屬性,例如手指數量、方向等。
  3. 把手勢附加到指定的視圖上。
  4. 撰寫手勢觸發時要執行的回應方法。

3. 手勢的七種狀態

// 尚未發生觸摸,所有手勢的預設狀態
UIGestureRecognizerStatePossible,
// 手勢已開始,但尚未改變或完成
UIGestureRecognizerStateBegan,
// 手勢狀態改變
UIGestureRecognizerStateChanged,
// 手勢完成
UIGestureRecognizerStateEnded,
// 手勢取消,恢復為 Possible
UIGestureRecognizerStateCancelled,
// 手勢失敗,恢復為 Possible
UIGestureRecognizerStateFailed,
// 成功識別到手勢
UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded

手勢識別的常用屬性包括 state(手勢狀態)與 view(手勢發生的視圖);常用方法則有 locationInView,用來取得手勢在對應視圖中的位置。

4. 完整範例

- (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 打造自然流暢的互動體驗。接下來不妨動手做個小實驗,把點按、拖動、旋轉都套在同一個視圖上,親身感受事件在響應者鏈中流轉的過程。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved