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

iOS 手勢操作完整整理:從 UIGestureRecognizer 到自訂手勢

編輯:iOS 開發綜合

一、UIGestureRecognizer 概觀

UIGestureRecognizer 是個抽象類別,真正在用的都是它的子類,每一個對應一種手勢:

  • UITapGestureRecognizer:點擊
  • UIPinchGestureRecognizer:兩指往內或往外撥動,也就是常用的縮放
  • UIRotationGestureRecognizer:旋轉
  • UISwipeGestureRecognizer:快速滑動
  • UIPanGestureRecognizer:拖移,速度較慢
  • UILongPressGestureRecognizer:長按

二、使用手勢的兩個步驟

(1) 建立手勢實例,並指定一個回呼方法。手勢開始、改變或結束時,該方法都會被呼叫。

(2) 把手勢加到需要辨識的 View 上。一個手勢實例只能綁一個 View;反過來說,一個 View 可以掛多個手勢。當觸摸落在 View 邊界內且軌跡符合預期,回呼就會觸發。

三、拖移(Pan)

UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];
snakeImageView.frame = CGRectMake(50, 50, 100, 160);

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[snakeImageView addGestureRecognizer:pan];
[self.view addSubview:snakeImageView];

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint t = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + t.x,
                                         recognizer.view.center.y + t.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
}

四、縮放(Pinch)

UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];

- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform,
                                                       recognizer.scale,
                                                       recognizer.scale);
    recognizer.scale = 1;
}

五、旋轉(Rotation)

UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)];
[snakeImageView addGestureRecognizer:rotate];

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

六、為多個 View 掛上手勢

記住原則:一個手勢實例只能加在一個 View 上。所以兩個 View 就得建立兩組手勢。

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *snake  = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];
    UIImageView *dragon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dragon.png"]];
    snake.frame  = CGRectMake(120, 120, 100, 160);
    dragon.frame = CGRectMake(50, 50, 100, 160);
    [self.view addSubview:snake];
    [self.view addSubview:dragon];

    for (UIView *view in self.view.subviews) {
        UIPanGestureRecognizer *pan    = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
        UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)];
        [view addGestureRecognizer:pan];
        [view addGestureRecognizer:pinch];
        [view addGestureRecognizer:rotate];
        view.userInteractionEnabled = YES;
    }
    self.view.backgroundColor = [UIColor whiteColor];
}

七、加入甩動慣性

快速拖曳後放開,視圖還會順著方向滑行一段,做法是監聽手勢是否結束,並讀取瞬間速度。

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint t = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + t.x,
                                         recognizer.view.center.y + t.y);
    [recognizer setTranslation:CGPointZero inView:self.view];

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint v = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf(v.x * v.x + v.y * v.y);
        CGFloat slideMult = magnitude / 200;
        CGFloat slideFactor = 0.1 * slideMult;

        CGPoint finalPoint = CGPointMake(recognizer.view.center.x + v.x * slideFactor,
                                         recognizer.view.center.y + v.y * slideFactor);
        finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

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

邏輯拆解:先算出速度向量的長度;速度小於 200 時會得到一個小於 1 的係數,滑行距離就很短;接著依速度與係數推算終點,再用 MIN/MAX 把終點夾在父視圖範圍內,最後用動畫滑過去。

八、讓兩個手勢同時觸發

手勢之間預設互斥。想讓蛇與龍同時被拖動或縮放,實作 UIGestureRecognizerDelegate 並回傳 YES:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)g
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)other
{
    return YES;
}

pan.delegate = self;
pinch.delegate = self;
rotate.delegate = self;

九、點擊(Tap)搭配音效

為了驗證 tap 效果,點一下螢幕就播放一段聲音,需要引入 AVFoundation.framework。

- (AVAudioPlayer *)loadWav:(NSString *)filename
{
    NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:@"wav"];
    NSError *error = nil;
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if (!player) {
        NSLog(@"載入失敗 %@: %@", url, error.localizedDescription);
    } else {
        [player prepareToPlay];
    }
    return player;
}

- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
    [self.chompPlayer play];
}

十、手勢之間的依賴關係

上面的做法有個缺陷:拖曳過程中也會觸發 tap。解法是宣告依賴:

[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer];

意思是只有當 pan 手勢失敗(也就是根本沒拖動)時,tap 才會觸發。輕微拖曳屬於 pan,音效自然就不會誤響。

十一、自訂手勢

自訂手勢繼承 UIGestureRecognizer,並覆寫 touchesBegan / touchesMoved / touchesEnded / touchesCancelled 四個方法。

// HappyGestureRecognizer.h
typedef enum { DirectionUnknown = 0, DirectionLeft, DirectionRight } Direction;

@interface HappyGestureRecognizer : UIGestureRecognizer
@property (assign) int tickleCount;
@property (assign) CGPoint curTickleStart;
@property (assign) Direction lastDirection;
@end
// HappyGestureRecognizer.m
#import "HappyGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>

#define REQUIRED_TICKLES 2
#define MOVE_AMT_PER_TICKLE 25

@implementation HappyGestureRecognizer

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

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    CGFloat moveAmt = point.x - self.curTickleStart.x;

    Direction curDirection = (moveAmt < 0) ? DirectionLeft : DirectionRight;
    if (ABS(moveAmt) < MOVE_AMT_PER_TICKLE) return;

    // 確認方向確實改變了
    if (self.lastDirection == DirectionUnknown ||
        (self.lastDirection == DirectionLeft  && curDirection == DirectionRight) ||
        (self.lastDirection == DirectionRight && curDirection == DirectionLeft)) {
        self.tickleCount++;
        self.curTickleStart = point;
        self.lastDirection = curDirection;

        // 次數達標就把手勢設為結束狀態,回呼才會被觸發
        if (self.state == UIGestureRecognizerStatePossible &&
            self.tickleCount > REQUIRED_TICKLES) {
            [self setState:UIGestureRecognizerStateEnded];
        }
    }
}

- (void)reset
{
    self.tickleCount = 0;
    self.curTickleStart = CGPointZero;
    self.lastDirection = DirectionUnknown;
    if (self.state == UIGestureRecognizerStatePossible) {
        [self setState:UIGestureRecognizerStateFailed];
    }
}

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

@end

使用方式與系統手勢相同:

- (void)handleHappy:(HappyGestureRecognizer *)recognizer
{
    [self.hehePlayer play];
}

邏輯是:先記錄起始座標,用移動後的 x 值判斷方向,若移動距離不足 MOVE_AMT_PER_TICKLE 就直接返回;方向一旦改變就累加次數,當左右來回次數超過門檻,手勢宣告成功並觸發回呼。在真機上按住某個 view 快速左右拖動,就會聽到笑聲。

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