萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 觸控事件處理指南:UIGestureRecognizer 與底層事件

前言:現代 iOS 觸控開發核心是手勢識別器

直接處理 `touchesBegan/Moved/Ended:` 已成歷史。`UIGestureRecognizer` 封裝狀態機、多點觸控、延遲識別、委派協調,是標準做法。本文介紹兩種實現層級。

方法一:UIGestureRecognizer 高層手勢識別(標準做法)

常用手勢類型

類別手勢典型用途
UITapGestureRecognizer單擊、雙擊、多點點擊按鈕替代、項目選擇、縮放重置
UIPinchGestureRecognizer雙指捏合圖片縮放、地圖縮放
UIRotationGestureRecognizer雙指旋轉圖片旋轉、物體旋轉
UISwipeGestureRecognizer快速滑動(上下左右)頁面切換、刪除、抽屜菜單
UIPanGestureRecognizer拖拽/平移視圖拖動、抽屜、彈簧動畫
UILongPressGestureRecognizer長按進入編輯模式、顯示菜單、預覽
UIScreenEdgePanGestureRecognizer邊緣滑動返回手勢、側邊欄呼出

完整範例:左右滑動切換視圖


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 目標視圖:只在這個範圍內識別滑動
    UIView *detectView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 280, 300)];
    detectView.backgroundColor = [UIColor blueColor];
    detectView.alpha = 0.6;
    [self.view addSubview:detectView];
    detectView.userInteractionEnabled = YES; // 關鍵!
    
    // 右滑手勢
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [detectView addGestureRecognizer:swipeRight];
    
    // 左滑手勢
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [detectView addGestureRecognizer:swipeLeft];
    
    // 可選:上/下滑
    // UISwipeGestureRecognizer *swipeUp = ... direction:UISwipeGestureRecognizerDirectionUp;
    // UISwipeGestureRecognizer *swipeDown = ... direction:UISwipeGestureRecognizerDirectionDown;
}

- (void)handleSwipe:(UISwipeGestureRecognizer *)recognizer {
    switch (recognizer.direction) {
        case UISwipeGestureRecognizerDirectionLeft:
            NSLog(@"向左滑動 → 下一頁/刪除/下一項");
            break;
        case UISwipeGestureRecognizerDirectionRight:
            NSLog(@"向右滑動 → 上一頁/返回/取消刪除");
            break;
        case UISwipeGestureRecognizerDirectionUp:
            NSLog(@"向上滑動 → 收起/刷新/展開");
            break;
        case UISwipeGestureRecognizerDirectionDown:
            NSLog(@"向下滑動 → 關閉/下拉刷新/收起鍵盤");
            break;
        default:
            break;
    }
}

手勢識別器關鍵屬性

  • delegate:實現 `UIGestureRecognizerDelegate` 協調多手勢(如同時識別、失敗要求)
  • cancelsTouchesInView:預設 YES,識別成功取消傳遞 touch 給視圖。設 NO 可同時處理
  • delaysTouchesBegan/Ended:延遲觸摸傳遞,避免閃爍
  • numberOfTapsRequired、`numberOfTouchesRequired`:點擊次數、手指數

委派協調範例:滑動與拖拽共存


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // 允許 Pan 與 Swipe 同時識別
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && 
           [otherGestureRecognizer isKindOfClass:[UISwipeGestureRecognizer class]];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // 單擊需等待雙擊失敗
    return [gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]] && 
           [otherGestureRecognizer isKindOfClass:[UITapGestureRecognizer class]] &&
           ((UITapGestureRecognizer *)otherGestureRecognizer).numberOfTapsRequired == 2;
}

方法二:GSEvent 底層事件注入(私有 API、僅供研究/測試)

警告:使用 `GraphicsServices` 私有框架,**App Store 會拒審**,僅適用於:

  • 自動化測試腳本
  • 越獄開發
  • 系統級工具開發
  • 安全研究

// 僅供參考,不可用於上架 App
#import 

- (void)simulateKeyPress:(char)keyChar {
    GSEventRecord header;
    GSHardwareKeyInfo keyInfo = {0};
    keyInfo.keyCode = keyChar; // 簡化,實際需映射鍵碼
    keyInfo.flags = 1; // key down
    
    memset(&header, 0, sizeof(header));
    header.type = kGSEventKeyDown;
    header.infoSize = sizeof(GSHardwareKeyInfo);
    header.timestamp = mach_absolute_time();
    
    struct { GSEventRecord h; GSHardwareKeyInfo k; } event = {header, keyInfo};
    GSSendEvent(&event, GSGetPurpleApplicationPort());
    
    // Key Up
    keyInfo.flags = 0;
    header.type = kGSEventKeyUp;
    header.timestamp = mach_absolute_time();
    struct { GSEventRecord h; GSHardwareKeyInfo k; } eventUp = {header, keyInfo};
    GSSendEvent(&eventUp, GSGetPurpleApplicationPort());
}

觸控事件傳遞鏈(Responder Chain)

觸摸發生
    ↓
UIApplication -> UIWindow -> 根視圖控制器 -> 視圖層級遍歷 (hitTest:withEvent:)
    ↓
找到第一響應者 (First Responder)
    ↂ
touchesBegan:withEvent: -> touchesMoved: -> touchesEnded:/touchesCancelled:
    ↓
若視圖未處理,沿響應者鏈向上傳遞
    ↓
UIWindow -> UIApplication -> AppDelegate

最佳實踐清單

  1. **優先用 UIGestureRecognizer**,勿重寫 touches 方法
  2. **設定 `cancelsTouchesInView = NO`** 避免攔截按鈕、ScrollView 滑動
  3. **正確設定 `delegate` 協調手勢衝突**
  4. **目標視圖 `userInteractionEnabled = YES`**
  5. **長按手勢需設定 `minimumPressDuration`、`allowableMovement`**
  6. **測試真機**,模擬器單點滑鼠無法模擬多點手勢
copyright © 萬盛學電腦網 all rights reserved