您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 手勢識別完全指南:從觸摸事件到 UIGestureRecognizer

編輯:iOS 程式設計技術

在 iOS 裡處理使用者互動,手勢識別幾乎是繞不開的一環。本文從觸摸事件的局限講起,梳理手勢識別器的使用步驟、狀態機制與常見子類,並附上完整的實作範例。

一、手勢識別與觸摸事件

若想監聽某個 view 上的觸摸事件,傳統做法有兩種:一是自定義一個 view,二是在其 touches 方法內部撰寫具體的處理邏輯。

然而,這種依賴 touches 方法的方式存在明顯缺陷:

  • 必須自定義 view,無法直接複用系統元件。
  • 監聽邏輯寫死在 view 內部,預設情況下外界物件無從得知觸摸的發生。
  • 難以精準區分使用者究竟做了哪種手勢。

正因如此,蘋果從 iOS 3.2 起推出了手勢識別功能(Gesture Recognizer),大幅降低了開發者在觸摸處理上的門檻。

二、手勢識別器 UIGestureRecognizer

UIGestureRecognizer 是一個抽象類,它定義了所有手勢的通用行為,真正處理具體手勢時需要用到它的各個子類。

使用手勢識別,大致遵循以下五個步驟:

  1. 建立手勢識別實例。
  2. 設定手勢屬性,例如需要幾根手指、滑動方向等。
  3. 將手勢識別附加到目標視圖上。
  4. 撰寫手勢觸發後的監聽方法。
  5. 在監聽方法中還原手勢屬性。例如取得縮放比例並套用後,記得把比例重設為 1,這樣後續手勢才能重新計算,避免出錯。

三、手勢的狀態機

與觸摸事件類似,手勢識別實例帶有一個 state 屬性,用於表達當前手勢所處的階段,它是枚舉類型:

  • UIGestureRecognizerStatePossible:尚未發生觸摸,是所有手勢的預設初始狀態。
  • UIGestureRecognizerStateBegan:手勢已開始但尚未改變或完成,類似 touchesBegan。
  • UIGestureRecognizerStateChanged:手勢正在變化中,類似 touchesMoved。
  • UIGestureRecognizerStateEnded:手勢完成,類似 touchesEnded。
  • UIGestureRecognizerStateCancelled:手勢被取消,回到 Possible 狀態(例如按下按鈕後卻從別處抬手)。
  • UIGestureRecognizerStateFailed:手勢識別失敗,回到 Possible 狀態。
  • UIGestureRecognizerStateRecognized:識別到手勢結束,數值等同於 Ended。

四、常見子類的專屬屬性

不同子類各自擁有獨特的屬性與方法,以下幾個較為常用:

輕點手勢:可設定點擊次數與手指數量。

tap.numberOfTapsRequired = 2;   //連續敲擊 2 次才觸發
tap.numberOfTouchesRequired = 2; //需要 2 根手指一起敲擊

旋轉手勢:可取得旋轉角度與旋轉速度。

CGFloat rotation; //旋轉角度
CGFloat velocity;   //旋轉速度

輕掃手勢:一個輕掃識別物件只能對應一個方向。

UISwipeGestureRecognizerDirection //掃動方向

拖拽手勢:可取得移動距離,並在需要時清除以重新計算。

- (CGPoint)translationInView:(nullable UIView *)view; //取得移動距離
[pan setTranslation:CGPointZero inView:self.view];    //清除移動距離

五、同時識別多個手勢

有時我們希望縮放與旋轉能同時進行。做法很簡單:先為手勢識別器設置代理,再實作相應的代理方法,即可支持多手勢並存。

六、完整實作範例

下面示範長按、旋轉、縮放、輕掃與拖拽等多種手勢的綁定方式:

#pragma mark - 長按手勢
- (IBAction)longPressBtnClick:(id)sender {
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longClick:)];
    [self.view addGestureRecognizer:longPress];
    longPress.delegate = self;
}
-(void)longClick:(UILongPressGestureRecognizer *)longPress {
    if(longPress.state==UIGestureRecognizerStateBegan) {
        NSLog(@"開始長按了~~");
    }
}
#pragma mark - 旋轉手勢
- (IBAction)rotateBtnClick {
    UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotateClick:)];
    [self.view addGestureRecognizer:rotate];
    rotate.delegate = self;
}
-(void)rotateClick:(UIRotationGestureRecognizer *)rotate {
    CGFloat ratation = rotate.rotation;
    self.headerView.transform = CGAffineTransformRotate(self.headerView.transform, ratation);
    rotate.rotation = 0; //清除累加的 rotation
}
#pragma mark - 縮放手勢
- (IBAction)pinchBtnClick {
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchClick:)];
    [self.view addGestureRecognizer:pinch];
    pinch.delegate = self;
}
-(void)pinchClick:(UIPinchGestureRecognizer *)pinch {
    CGFloat scale = pinch.scale;
    self.headerView.transform = CGAffineTransformScale(self.headerView.transform, scale, scale);
    pinch.scale = 1; //同樣清除
}
#pragma mark - 輕掃手勢
- (IBAction)swipeBtnClick {
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeClick:)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipe];
    UISwipeGestureRecognizer *swipe2 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeClick:)];
    swipe2.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipe2];
}
-(void)swipeClick:(UISwipeGestureRecognizer *)swipe {
    if (swipe.direction==UISwipeGestureRecognizerDirectionRight) {
        [UIView animateWithDuration:0.3 animations:^{ self.headerView.transform = CGAffineTransformTranslate(self.headerView.transform, 100, 0); }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{ self.headerView.transform = CGAffineTransformIdentity; }];
        }];
    } else if (swipe.direction==UISwipeGestureRecognizerDirectionLeft) {
        [UIView animateWithDuration:0.3 animations:^{ self.headerView.transform = CGAffineTransformTranslate(self.headerView.transform, -100, 0); }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{ self.headerView.transform = CGAffineTransformIdentity; }];
        }];
    }
}
#pragma mark - 拖拽手勢
- (IBAction)panBtnClick {
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panClick:)];
    [self.view addGestureRecognizer:pan];
}
-(void)panClick:(UIPanGestureRecognizer *)pan {
    CGPoint point = [pan translationInView:self.view];
    self.headerView.transform = CGAffineTransformTranslate(self.headerView.transform, point.x, point.y);
    [pan setTranslation:CGPointZero inView:self.view];
}
//手勢識別代理實現
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved