您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 手勢識別器完整整理:六大子類與代理機制

編輯:iOS 開發綜合

一、傳統的觸摸監聽做法

若想監聽某個 view 上的觸摸事件而不使用手勢,步驟是:先自訂一個 view,再在其 touches 方法內實作具體處理邏輯。

這種做法缺點明顯:

  • 一定要自訂 view,無法直接套用於既有控件。
  • 因為監聽邏輯寫在 view 內部,外界物件預設無法得知觸摸狀況。
  • 不容易區分使用者究竟做了哪種手勢。

iOS 3.2 之後,Apple 推出了手勢識別功能(Gesture Recognizer),大幅簡化了觸摸處理的開發難度。

二、手勢識別器簡介

手勢識別的核心型別是 UIGestureRecognizer。透過它,可以輕鬆辨識使用者在某個 view 上所做的常見手勢。

它是一個抽象類別,只定義所有手勢的共同行為,具體辨識必須靠子類完成。常見子類如下:

  • UITapGestureRecognizer(敲擊)
  • UIPinchGestureRecognizer(捏合,用於縮放)
  • UIPanGestureRecognizer(拖曳)
  • UISwipeGestureRecognizer(輕掃)
  • UIRotationGestureRecognizer(旋轉)
  • UILongPressGestureRecognizer(長按)

三、常見屬性與方法

UIGestureRecognizer 繼承自 NSObject,以下是開發中最常打交道的成員:

// 建立時指定目標與事件
- (instancetype)initWithTarget:(nullable id)target action:(nullable SEL)action;
- (void)addTarget:(id)target action:(SEL)action;
- (void)removeTarget:(nullable id)target action:(nullable SEL)action;

@property(nonatomic, readonly) UIGestureRecognizerState state;   // 手勢狀態
@property(nullable, nonatomic, weak) id delegate;                // 代理
@property(nonatomic, getter=isEnabled) BOOL enabled;             // 是否啟用,預設 YES
@property(nullable, nonatomic, readonly) UIView *view;           // 所屬視圖

// 預設 YES:手勢一旦識別成功,就送 touchesCancelled 給 touchView
@property(nonatomic) BOOL cancelsTouchesInView;

// 預設 NO:設為 YES 後,手勢識別成功前不再把 touch 對象分發給 touchView
@property(nonatomic) BOOL delaysTouchesBegan;

// 預設 YES:手勢識別成功前不呼叫 touchesEnded
@property(nonatomic) BOOL delaysTouchesEnded;

// 要求另一個識別器先失敗,自己才參與識別
- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer;

// 觸摸點相關
- (CGPoint)locationInView:(nullable UIView *)view;
- (NSUInteger)numberOfTouches;
- (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(nullable UIView *)view;

四、代理方法

注意:只要頁面上有多個手勢並存,就必須設定代理。

// 是否允許開始識別
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;

// 是否允許與其他手勢同時識別(預設不允許)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;

// 兩者互斥時的優先順序,iOS 7 起可用
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;

// 是否接收觸摸點/按壓
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
         shouldReceiveTouch:(UITouch *)touch;
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
         shouldReceivePress:(UIPress *)press;

關於同時識別的判定有一個容易搞錯的細節:兩個識別器的代理方法中,只要任一邊回傳 YES,這兩個手勢就能同時識別;只有兩邊都回傳 NO,才代表互斥。

五、各子類的專屬屬性

1. UITapGestureRecognizer(敲擊)

@property (nonatomic) NSUInteger numberOfTapsRequired;      // 需連續敲幾次,預設 1
@property (nonatomic) NSUInteger numberOfTouchesRequired;   // 需幾根手指,預設 1

2. UIPinchGestureRecognizer(捏合/縮放)

模擬器可用 option + shift 拖曳來模擬雙指操作。

@property (nonatomic) CGFloat scale;          // 縮放比例
@property (nonatomic, readonly) CGFloat velocity;  // 縮放速度

3. UIPanGestureRecognizer(拖曳)

@property (nonatomic) NSUInteger minimumNumberOfTouches;
@property (nonatomic) NSUInteger maximumNumberOfTouches;

- (CGPoint)translationInView:(nullable UIView *)view;              // 相對指定 view 的位移
- (void)setTranslation:(CGPoint)translation inView:(nullable UIView *)view;
- (CGPoint)velocityInView:(nullable UIView *)view;                 // 拖曳速度

4. UISwipeGestureRecognizer(輕掃)

@property(nonatomic) NSUInteger numberOfTouchesRequired;
@property(nonatomic) UISwipeGestureRecognizerDirection direction;

5. UIRotationGestureRecognizer(旋轉)

@property (nonatomic) CGFloat rotation;             // 旋轉角度(弧度)
@property (nonatomic, readonly) CGFloat velocity;   // 旋轉速度

6. UILongPressGestureRecognizer(長按)

注意:長按手勢預設會觸發兩次(began 與 ended),若只想處理一次,記得判斷 state。

@property (nonatomic) NSUInteger numberOfTapsRequired;
@property (nonatomic) NSUInteger numberOfTouchesRequired;
@property (nonatomic) CFTimeInterval minimumPressDuration;   // 最短長按時間
@property (nonatomic) CGFloat allowableMovement;             // 允許移動的距離

六、實作示範

把六種手勢一次掛到同一個 imageView 上,並在代理中允許同時識別,就能做到縮放、旋轉、拖曳同時生效的效果。

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpTap];
    [self setUpLongPress];
    [self setUpSwipe];
    [self setUpRotation];
    [self setUpPinch];
    [self setUpPan];
}

#pragma mark - 點按
- (void)setUpTap {
    UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                       action:@selector(actionUpTap)];
    gr.delegate = self;   // 多手勢並存時必須設代理
    [_imageView addGestureRecognizer:gr];
}

#pragma mark - 旋轉
- (void)setUpRotation {
    UIRotationGestureRecognizer *gr = [[UIRotationGestureRecognizer alloc]
                                       initWithTarget:self action:@selector(actionRotation:)];
    gr.delegate = self;
    [_imageView addGestureRecognizer:gr];
}

- (void)actionRotation:(UIRotationGestureRecognizer *)rotation {
    _imageView.transform = CGAffineTransformRotate(_imageView.transform, rotation.rotation);
    rotation.rotation = 0;   // 復位,否則角度會持續累加
}

#pragma mark - 縮放
- (void)actionPinch:(UIPinchGestureRecognizer *)pinch {
    _imageView.transform = CGAffineTransformScale(_imageView.transform, pinch.scale, pinch.scale);
    pinch.scale = 1;         // 同樣要復位
}

#pragma mark - 拖曳
- (void)actionPan:(UIPanGestureRecognizer *)pan {
    CGPoint trans = [pan translationInView:_imageView];
    _imageView.transform = CGAffineTransformTranslate(_imageView.transform, trans.x, trans.y);
    [pan setTranslation:CGPointZero inView:_imageView];   // 復位
}

#pragma mark - 輕掃(各方向需各自建立一個實例)
- (void)setUpSwipe {
    UISwipeGestureRecognizer *right = [[UISwipeGestureRecognizer alloc]
                                       initWithTarget:self action:@selector(actionSwipe)];
    [_imageView addGestureRecognizer:right];   // 預設向右

    UISwipeGestureRecognizer *left = [[UISwipeGestureRecognizer alloc]
                                      initWithTarget:self action:@selector(actionSwipe)];
    left.direction = UISwipeGestureRecognizerDirectionLeft;
    [_imageView addGestureRecognizer:left];
}

#pragma mark - 代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { return YES; }

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
         shouldReceiveTouch:(UITouch *)touch { return YES; }

實務上有兩個地方特別容易忘記:一是縮放與旋轉的 handler 結尾必須把 scale/rotation 復位,否則第二次手勢會在上次的基礎上繼續累加;二是輕掃手勢每個方向都得各自建立一個實例,無法用一個物件同時接收多個方向。

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