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

iOS 手勢操作完整整理:拖動、捏合、旋轉、點按、長按、輕掃與自定義

編輯:iOS 開發綜合

手勢是行動裝置直覺操作的基礎,本文把 iOS 六大內建手勢與自定義手勢的用法、狀態機制與實作細節一次講清楚。

一、UIGestureRecognizer 概覽

自 iOS 3.2 起,系統就提供了幾個常用的手勢識別器子類,開發者不必自己從觸摸事件下手,直接取用即可:

  • UIPanGestureRecognizer(拖動)
  • UIPinchGestureRecognizer(捏合)
  • UIRotationGestureRecognizer(旋轉)
  • UITapGestureRecognizer(點按)
  • UILongPressGestureRecognizer(長按)
  • 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;
// 以上方法宣告在 UIGestureRecognizer (UIGestureRecognizerProtected) 分類中

類別繼承關係如下圖:

二、離散型與連續型手勢

六種手勢中,只有 UITapGestureRecognizer 屬於離散型:一旦識別就無法取消,回調也只會觸發一次。其餘五種都是連續型,會在移動過程中反覆觸發回調,而且辨識後仍可取消。

狀態列舉如下:

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

以旋轉手勢為例說明連續型的行為:雙指按在螢幕上不動時尚未識別,但觸摸開始事件已觸發,狀態為 0;開始旋轉後識別成立,回調被呼叫,狀態短暫變為 1;接著因為手勢持續,狀態轉為 2 並反覆觸發回調;手指離開後狀態變為 3,回調再觸發最後一次。離散型的點按則是「要麼成功、要麼失敗」,手指離開的瞬間才判定並呼叫一次回調。

三、使用手勢的三個步驟

  1. 建立手勢識別器實例,並在初始化時指定手勢成立、改變或結束時要執行的回調方法。
  2. 設定識別器的相關屬性(例如點擊次數、最小按壓時間、輕掃方向),這一步是選用。
  3. 把手勢加入需要監聽的 View。觸摸落在該 View 範圍內且手勢符合條件時,回調才會被觸發。

要注意的是:一個手勢只能綁一個 View,但一個 View 可以掛多個手勢。另外建議以真機測試,模擬器操作不夠真實,容易誤判手勢失效(在模擬器上測試捏合與旋轉時,按住 option 鍵再用觸控板或滑鼠操作)。

四、實作範例

功能設計:兩個 UIImageView 各自綁定拖動、捏合、旋轉、點按與長按;輕掃與自定義手勢則掛在根視圖上。

  • 拖動:移動圖片位置,並依速度向量帶一點慣性滑行
  • 捏合:縮放圖片
  • 旋轉:旋轉圖片角度
  • 點按:單指雙擊還原縮放、角度與不透明度
  • 長按:把不透明度設為 0.7
  • 輕掃:左右輕掃讓兩張圖以垂直居中為基準上下錯開
  • 自定義手勢:左右來回掃動三次以上,讓兩張圖以水平居中為基準左右錯開

// 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

// ViewController.m 手勢處理
- (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) {
        // 依速度向量長度推算滑行距離,小於 200 時滑行很不明顯
        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;
    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();
}

// 綁定手勢
- (void)bindPan:(UIImageView *)imgVCustom {
    UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [imgVCustom addGestureRecognizer:recognizer];
}
- (void)bindPinch:(UIImageView *)imgVCustom {
    UIPinchGestureRecognizer *recognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    [imgVCustom addGestureRecognizer:recognizer];
}
- (void)bindRotation:(UIImageView *)imgVCustom {
    UIRotationGestureRecognizer *recognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
    [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 addGestureRecognizer:_customGestureRecognizer];
}
- (void)layoutUI {
    UIImage *img = [UIImage imageNamed:@"Emoticon_tusiji_icon"];
    CGFloat cornerRadius = img.size.width;
    _imgV = [[UIImageView alloc] initWithImage:img];
    _imgV.frame = CGRectMake(20.0, 20.0, cornerRadius * 2, cornerRadius * 2);
    _imgV.userInteractionEnabled = YES;
    _imgV.layer.masksToBounds = YES;
    _imgV.layer.cornerRadius = cornerRadius;
    _imgV.layer.borderWidth = 2.0;
    _imgV.layer.borderColor = [UIColor grayColor].CGColor;
    [self.view addSubview:_imgV];

    img = [UIImage imageNamed:@"Emoticon_tusiji_icon2"];
    cornerRadius = img.size.width;
    _imgV2 = [[UIImageView alloc] initWithImage:img];
    _imgV2.frame = CGRectMake(20.0, 40.0 + _imgV.frame.size.height, cornerRadius * 2, cornerRadius * 2);
    _imgV2.userInteractionEnabled = YES;
    _imgV2.layer.masksToBounds = YES;
    _imgV2.layer.cornerRadius = cornerRadius;
    _imgV2.layer.borderWidth = 2.0;
    _imgV2.layer.borderColor = [UIColor orangeColor].CGColor;
    [self.view addSubview:_imgV2];

    for (UIImageView *v in @[_imgV, _imgV2]) {
        [self bindPan:v];
        [self bindPinch:v];
        [self bindRotation:v];
        [self bindTap:v];
        [self bindLongPress:v];
    }
    [self bingCustomGestureRecognizer];
    [self bindSwipe];
}
@end

掌握手勢狀態的變化,是寫好互動的關鍵;特別是連續型手勢會高頻觸發回調,回調裡要避免做重運算或重繪以外的昂貴操作。

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