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

iOS 觸摸事件與六大手勢識別器完整實作

編輯:iOS 開發綜合

iOS 的事件可以分成三類:觸摸事件、加速計(motion)事件、遠程控制事件。能接收並處理這些事件的物件被稱為「響應者物件」,前提是必須繼承 UIResponder。UIApplication、UIViewController、UIView 都在其列。

一、UIResponder 提供的事件處理方法

// 觸摸事件
touchesBegan:withEvent:
touchesMoved:withEvent:
touchesEnded:withEvent:
touchesCancelled:withEvent:

// 加速計事件
motionBegan:withEvent:
motionEnded:withEvent:
motionCancelled:withEvent:

// 遠程控制事件
remoteControlReceivedWithEvent:

二、UIView 的四個觸摸方法

/**
 * 手指開始觸摸 view 時呼叫
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s", __func__);
}

/**
 * 手指在 view 上移動時呼叫(會頻繁觸發)
 */
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s", __func__);
}

/**
 * 手指離開 view 時呼叫
 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s", __func__);
}

/**
 * 觸摸被系統事件打斷時呼叫(例如來電、通知彈出)
 */
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s", __func__);
}

一次完整的觸摸必然會依序觸發 began → moved(若手指有移動)→ ended。cancelled 則只在被打斷時出現,取代 ended。

三、UITouch:一根手指一個物件

一根手指接觸螢幕,系統就會產生一個與之關聯的 UITouch 物件。手指移動時,系統更新的是同一個 UITouch 物件,讓它持續保存最新的位置資訊;手指離開螢幕,對應的 UITouch 才被銷毀。

@interface UITouch : NSObject
@property(nonatomic, readonly) NSTimeInterval timestamp;   // 時間戳
@property(nonatomic, readonly) UITouchPhase phase;         // 觸摸階段
@property(nonatomic, readonly) NSUInteger tapCount;        // 短時間內的點擊次數
@property(nonatomic, readonly) CGFloat majorRadius;        // 觸摸半徑(iOS 8+)
@property(nonatomic, readonly) CGFloat majorRadiusTolerance;
@property(nullable, nonatomic, readonly, strong) UIWindow *window;  // 所在視窗
@property(nullable, nonatomic, readonly, strong) UIView *view;      // 所在視圖
@property(nullable, nonatomic, readonly, copy) NSArray <UIGestureRecognizer *> *gestureRecognizers;

// 取得相對於指定 view 的當前位置
- (CGPoint)locationInView:(nullable UIView *)view;

// 取得相對於指定 view 的上一個位置
- (CGPoint)previousLocationInView:(nullable UIView *)view;

// 觸壓力道,1.0 代表一般觸壓(iOS 9+,需 3D Touch 硬體)
@property(nonatomic, readonly) CGFloat force;
@property(nonatomic, readonly) CGFloat maximumPossibleForce;
@end

實作:讓 view 跟著手指移動

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 取得觸摸物件
    UITouch *touch = [touches anyObject];

    // 當前位置與上一個位置
    CGPoint curP = [touch locationInView:self];
    CGPoint preP = [touch previousLocationInView:self];

    // 算出位移量
    CGFloat offsetX = curP.x - preP.x;
    CGFloat offsetY = curP.y - preP.y;

    // 套用到形變上
    self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
}

這裡用 transform 而非直接改 frame 或 center,是因為 transform 不會觸發 Auto Layout 重新計算,效能更好,也不會與約束打架。

四、事件如何產生與傳遞

觸摸發生後,系統把事件放進 UIApplication 管理的事件佇列。UIApplication 取出最前面的事件,交給主視窗處理。主視窗在視圖層級結構中找出最合適的 view,呼叫它的 touches 方法。

傳遞方向是由父控制項傳向子控制項。這意味著:如果父控制項根本收不到觸摸事件,子控制項也就不可能收到。

找尋「最合適控制項」的演算法是:

  1. 判斷自己能否接收觸摸事件(userInteractionEnabled、hidden、alpha)。
  2. 判斷觸摸點是否在自己身上。
  3. 從後往前遍歷子控制項,對每個子控制項重複上述兩個步驟。
  4. 若都沒有符合條件的子控制項,就由自己承擔。

這套邏輯由 hitTest:withEvent: 實作,而「點在不在自己身上」由 pointInside:withEvent: 判斷。底層實作如下:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    // 1. 判斷當前控制項是否能接收觸摸事件
    if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) {
        return nil;
    }

    // 2. 判斷觸摸點是否在當前控制項上
    if ([self pointInside:point withEvent:event] == NO) {
        return nil;
    }

    // 3. 從後往前遍歷子控制項
    NSInteger count = self.subviews.count;
    for (NSInteger i = count - 1; i >= 0; i--) {
        UIView *childView = self.subviews[i];

        // 把座標系從自己轉換到子控制項
        CGPoint childPoint = [self convertPoint:point toView:childView];

        // 遞迴尋找
        UIView *fitView = [childView hitTest:childPoint withEvent:event];
        if (fitView) {
            return fitView;
        }
    }

    // 沒有比自己更合適的,回傳自己
    return self;
}

從後往前遍歷,正是「畫面上層優先」這條規則的由來。

五、為什麼需要手勢識別器

用 touches 方法監聽有明顯缺點:想自訂一個可重用的「點擊」元件,就得自己判斷 tapCount、判斷位移範圍、判斷時間間隔,每個自訂 view 都要重寫一遍。因此 iOS 3.2 之後蘋果推出了 UIGestureRecognizer。

它是抽象類別,真正處理具體手勢的是它的子類:

// 點按
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];

// 長按(預設最小長按時間 0.5 秒)
UILongPressGestureRecognizer *longP = [[UILongPressGestureRecognizer alloc] initWithTarget:target action:action];

// 輕掃(預設方向為向右)
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:target action:action];

// 旋轉
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:target action:action];

// 捏合縮放
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:target action:action];

// 拖移
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:action];

六、實際運用

@interface ViewController () <UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation ViewController

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

#pragma mark - 手勢代理方法

// 是否允許開始觸發手勢
// - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
//     return NO;
// }

// 是否允許同時支援多個手勢(預設不支援)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

// 是否接收手指的觸摸點
// - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//     CGPoint curP = [touch locationInView:self.imageView];
//     if (curP.x < self.imageView.bounds.size.width * 0.5) {
//         return NO;
//     }
//     return YES;
// }

#pragma mark - 點按手勢
- (void)setUpTap {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    tap.delegate = self;
    [_imageView addGestureRecognizer:tap];
}

- (void)tap:(UITapGestureRecognizer *)tap {
    NSLog(@"%s", __func__);
}

#pragma mark - 長按手勢
- (void)setUpLongPress {
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.imageView addGestureRecognizer:longPress];
}

- (void)longPress:(UILongPressGestureRecognizer *)longPress {
    // 只在開始時處理一次,避免連續觸發
    if (longPress.state == UIGestureRecognizerStateBegan) {
        NSLog(@"%s", __func__);
    }
}

#pragma mark - 輕掃手勢
- (void)setUpSwipe {
    // 預設方向為向右
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe)];
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    [self.imageView addGestureRecognizer:swipe];

    // 一個輕掃手勢只支援一個方向,想要多方向就必須建立多個
    UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe)];
    swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
    [self.imageView addGestureRecognizer:swipeDown];
}

- (void)swipe {
    NSLog(@"%s", __func__);
}

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

- (void)rotation:(UIRotationGestureRecognizer *)rotation {
    // 回報的角度是相對於「最開始」的位置,用後必須歸零
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, rotation.rotation);
    rotation.rotation = 0;
}

#pragma mark - 捏合手勢
- (void)setUpPinch {
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
    pinch.delegate = self;
    [self.imageView addGestureRecognizer:pinch];
}

- (void)pinch:(UIPinchGestureRecognizer *)pinch {
    self.imageView.transform = CGAffineTransformScale(self.imageView.transform, pinch.scale, pinch.scale);
    // scale 同樣是相對值,必須歸零成 1
    pinch.scale = 1;
}

#pragma mark - 拖移手勢
- (void)setUpPan {
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.imageView addGestureRecognizer:pan];
}

- (void)pan:(UIPanGestureRecognizer *)pan {
    // translationInView 回報的是自上次呼叫以來的位移
    CGPoint transP = [pan translationInView:self.imageView];
    self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, transP.x, transP.y);
    // 用後歸零
    [pan setTranslation:CGPointZero inView:self.imageView];
}

@end

幾個實務重點

  • 相對值必須歸零。rotation、scale、translation 回報的都是「相對於上次」的增量,忘記重設就會出現位移或縮放愈來愈誇張的 bug。這是最常見的失誤。
  • 多手勢並存要設 delegate。若不實作 shouldRecognizeSimultaneouslyWith 並回傳 YES,多個手勢會互相搶佔,例如無法同時旋轉與縮放。
  • 長按要判斷 state。長按會持續觸發,通常只在 UIGestureRecognizerStateBegan 時處理一次。
  • 手勢與 touches 不要混用。同一個 view 上兩者並存容易出現行為衝突,優先選用手勢。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved