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

iOS 七種手勢完整實戰:拖動、捏合、旋轉、點按、長按、輕掃與自定義手勢

編輯:iOS 開發綜合

手勢在 iOS 開發裡幾乎無所不在,本文用一個可直接跑起來的 Demo,把七種手勢一次講透。

一、UIGestureRecognizer 概覽

手勢識別大幅提升了行動裝置的操作效率。從 iOS 3.2 起,系統提供了幾個現成的子類,我們可以直接取用:

  1. UIPanGestureRecognizer(拖動)
  2. UIPinchGestureRecognizer(捏合)
  3. UIRotationGestureRecognizer(旋轉)
  4. UITapGestureRecognizer(點按)
  5. UILongPressGestureRecognizer(長按)
  6. UISwipeGestureRecognizer(輕掃)

若這些都不夠用,也可以繼承 UIGestureRecognizer 自己寫一個。自定義時需引入 <UIKit/UIGestureRecognizerSubclass.h>,並實作下列方法:

- (void)reset;
- (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;

繼承關係如下:

二、離散型 vs 連續型手勢

六種系統手勢中,只有 UITapGestureRecognizer 是離散型:一旦識別就無法取消,且回呼方法只會被呼叫一次。

其餘五種都是連續型:回呼方法會被多次呼叫,而且在識別後仍可取消。從下面的示意圖能清楚看出呼叫次數的差異。

typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
    UIGestureRecognizerStatePossible,   // 尚未識別,可能已觸發觸控事件(預設狀態)
    UIGestureRecognizerStateBegan,      // 手勢開始,已被識別但尚未完成
    UIGestureRecognizerStateChanged,    // 手勢狀態改變
    UIGestureRecognizerStateEnded,      // 手勢完成(手指已離開)
    UIGestureRecognizerStateCancelled,  // 手勢被取消,回到預設狀態
    UIGestureRecognizerStateFailed,     // 識別失敗,回到預設狀態
    UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
};

以旋轉為例走一遍:兩指按下但不動,此時尚未識別(狀態 0,Possible),但觸控開始事件已經觸發;開始旋轉後被識別,狀態短暫變為 1(Began),接著進入 2(Changed)並持續呼叫回呼;手指離開時變為 3(Ended),再呼叫一次。相較之下,離散型的點按只有「識別成功」或「失敗」兩種結局。

三、使用手勢的三個步驟

  1. 建立手勢識別器實例,並指定手勢開始/改變/結束時要執行的回呼方法。
  2. 設定識別器的相關屬性(非必填)。
  3. 把手勢加到需要監聽的 View 上。當觸控落在該 View 邊界內且符合預定條件時,就會觸發回呼。

要注意:一個手勢只能綁一個 View,但一個 View 可以綁多個手勢。另外建議多在真機上測試,模擬器操作起來不太順手,容易誤判為「手勢沒反應」。(在模擬器上測捏合與旋轉時,按住 option 鍵再用觸控板或滑鼠操作。)

四、Demo 功能設計

兩個 UIImageView 各自綁定「拖動、捏合、旋轉、點按、長按」,而「輕掃」與自定義手勢則掛在根視圖 UIView 上:

· 拖動:移動圖片位置
· 捏合:縮放圖片
· 旋轉:旋轉圖片角度
· 點按(雙擊):還原縮放、角度與不透明度
· 長按:將不透明度設為 0.7
· 輕掃:左右輕掃讓兩張圖垂直居中並錯開特定偏移
· 自定義手勢:左右來回掃動達三次以上,讓兩張圖水平居中並錯開偏移

五、自定義手勢:KMGestureRecognizer

KMGestureRecognizer.h

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, Direction) {
    DirectionUnknown,
    DirectionLeft,
    DirectionRight
};

@interface KMGestureRecognizer : UIGestureRecognizer
@property (assign, nonatomic) NSUInteger tickleCount;        // 撓癢次數
@property (assign, nonatomic) CGPoint currentTickleStart;    // 本次撓癢起點
@property (assign, nonatomic) Direction lastDirection;       // 最後一次方向
@end

KMGestureRecognizer.m

#import "KMGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>

@implementation KMGestureRecognizer

#define kMinTickleSpacing 20.0
#define kMaxTickleCount   3

- (void)reset {
    _tickleCount = 0;
    _currentTickleStart = CGPointZero;
    _lastDirection = DirectionUnknown;
    if (self.state == UIGestureRecognizerStatePossible) {
        self.state = UIGestureRecognizerStateFailed;
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    _currentTickleStart = [touch locationInView:self.view];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint tickleEnd = [touch locationInView:self.view];
    CGFloat tickleSpacing = tickleEnd.x - _currentTickleStart.x;
    Direction currentDirection = tickleSpacing < 0 ? DirectionLeft : DirectionRight;

    // 位移必須夠大才算一次有效掃動
    if (ABS(tickleSpacing) >= kMinTickleSpacing) {
        // 方向必須與上一次相反
        if (_lastDirection == DirectionUnknown ||
            (_lastDirection == DirectionLeft  && currentDirection == DirectionRight) ||
            (_lastDirection == DirectionRight && currentDirection == DirectionLeft)) {
            _tickleCount++;
            _currentTickleStart = tickleEnd;
            _lastDirection = currentDirection;

            if (_tickleCount >= kMaxTickleCount && self.state == UIGestureRecognizerStatePossible) {
                self.state = UIGestureRecognizerStateEnded;   // 手勢成立,觸發回呼
            }
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event     { [self reset]; }
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self reset]; }

@end

這段實作的巧思在於:它只比對 X 軸位移,並要求相鄰兩次掃動方向必須相反,累計三次才算成立;reset 中主動把狀態設為 Failed,確保辨識失敗時能乾淨收尾。

六、手勢處理方法

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    [recognizer.view.superview bringSubviewToFront:recognizer.view];
    CGPoint center = recognizer.view.center;
    CGFloat cornerRadius = recognizer.view.frame.size.width / 2;
    CGPoint translation = [recognizer translationInView:self.view];

    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];   // 歸零,避免位移累加

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        // 依速度向量長度推算滑行距離,過小則不滑
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
        float slideFactor = 0.1 * slideMult;

        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),
                                         center.y + (velocity.y * slideFactor));
        // 限制在邊界內,避免滑出畫面
        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius), self.view.bounds.size.width  - cornerRadius);
        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius), self.view.bounds.size.height - cornerRadius);

        [UIView animateWithDuration:slideFactor * 2 delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{ recognizer.view.center = finalPoint; }
                         completion:nil];
    }
}

- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer {
    CGFloat scale = recognizer.scale;
    // 用 CGAffineTransformScale 才能「在既有基礎上累加」
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, scale, scale);
    recognizer.scale = 1.0;
}

- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer {
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
    recognizer.rotation = 0.0;
}

- (void)handleTap:(UITapGestureRecognizer *)recognizer {
    UIView *view = recognizer.view;
    view.transform = CGAffineTransformMakeScale(1.0, 1.0);
    view.transform = CGAffineTransformMakeRotation(0.0);
    view.alpha = 1.0;
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer {
    recognizer.view.alpha = 0.7;
}

- (void)handleSwipe:(UISwipeGestureRecognizer *)recognizer {
    void (^positionOperation)() = ^() {
        CGPoint newPoint = recognizer.view.center;
        newPoint.y -= 20.0;
        _imgV.center = newPoint;
        newPoint.y += 40.0;
        _imgV2.center = newPoint;
    };

    switch (recognizer.direction) {
        case UISwipeGestureRecognizerDirectionRight: positionOperation(); break;
        case UISwipeGestureRecognizerDirectionLeft:  positionOperation(); break;
        default: break;
    }
}

- (void)handleCustomGestureRecognizer:(KMGestureRecognizer *)recognizer {
    void (^positionOperation)() = ^() {
        CGPoint newPoint = recognizer.view.center;
        newPoint.x -= 20.0;
        _imgV.center = newPoint;
        newPoint.x += 40.0;
        _imgV2.center = newPoint;
    };
    positionOperation();
}

這裡有個容易忽略的細節:UIPanGestureRecognizer 每回合都要呼叫 setTranslation:inView: 歸零,否則位移會不斷疊加;捏合與旋轉同理,處理完就把 scale/rotation 重設。另外 CGAffineTransformScale 是「在當前基礎上疊加」,而 CGAffineTransformMakeScale 是「從原始大小重算」,兩者不可混用。

七、綁定手勢

- (void)bindPan:(UIImageView *)imgVCustom {
    UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [imgVCustom addGestureRecognizer:recognizer];
}

- (void)bindTap:(UIImageView *)imgVCustom {
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    recognizer.numberOfTapsRequired = 2;    // 雙擊才觸發
    recognizer.numberOfTouchesRequired = 1;
    [imgVCustom addGestureRecognizer:recognizer];
}

- (void)bindLongPress:(UIImageView *)imgVCustom {
    UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    recognizer.minimumPressDuration = 0.5;  // 預設即為 0.5 秒
    [imgVCustom addGestureRecognizer:recognizer];
}

// 輕掃:四個方向需各自定義一個手勢
- (void)bindSwipe {
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    recognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:recognizer];
    [recognizer requireGestureRecognizerToFail:_customGestureRecognizer];   // 讓自定義手勢優先

    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    recognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:recognizer];
    [recognizer requireGestureRecognizerToFail:_customGestureRecognizer];
}

- (void)bingCustomGestureRecognizer {
    _customGestureRecognizer = [[KMGestureRecognizer alloc] initWithTarget:self action:@selector(handleCustomGestureRecognizer:)];
    [self.view addSubview:_customGestureRecognizer];
}

最後記得順序:因為要處理手勢優先權,必須先綁定自定義撓癢手勢,再綁定輕掃,這樣 requireGestureRecognizerToFail: 才有對象可指。

以上就是本文的全部內容,希望能幫助到大家。

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