您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 開發中的觸摸事件與手勢處理詳解

編輯:iOS 相關教學

一、事件的分類與 UIResponder

iOS 中的事件主要分為三類:觸摸事件、加速計事件、遠程控制事件。只有繼承了 UIResponder 的物件才能接收並處理事件,這類物件被稱為「響應者物件」。UIApplication、UIViewController、UIView 都繼承自 UIResponder。

UIResponder 內部提供了對應的處理方法:

  • 觸摸事件:touchesBegan:withEvent:、touchesMoved:withEvent:、touchesEnded:withEvent:、touchesCancelled:withEvent:
  • 加速計事件:motionBegan:withEvent:、motionEnded:withEvent:、motionCancelled:withEvent:
  • 遠程控制事件:remoteControlReceivedWithEvent:
/** 手指開始觸摸 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 這三個方法。

二、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 NS_AVAILABLE_IOS(8_0);
@property (nonatomic, readonly) CGFloat majorRadiusTolerance NS_AVAILABLE_IOS(8_0);
@property (nullable, nonatomic, readonly, strong) UIWindow *window;
@property (nullable, nonatomic, readonly, strong) UIView *view;
@property (nullable, nonatomic, readonly, copy) NSArray<UIGestureRecognizer *> *gestureRecognizers;

// 取得目前位置
- (CGPoint)locationInView:(nullable UIView *)view;
// 取得上一個觸摸點的位置
- (CGPoint)previousLocationInView:(nullable UIView *)view;

// 觸摸力度,1.0 代表一般觸摸
@property (nonatomic, readonly) CGFloat force NS_AVAILABLE_IOS(9_0);
// 此輸入裝置可能的最大力度
@property (nonatomic, readonly) CGFloat maximumPossibleForce NS_AVAILABLE_IOS(9_0);
@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);
}

關鍵就是利用 UITouch 物件中保存的位置資訊算出位移量。

三、事件的產生與傳遞

觸摸事件產生後,系統會把它加入一個由 UIApplication 管理的事件佇列。UIApplication 從佇列中取出最前面的事件,發送給應用程式的主窗口;主窗口會在視圖層次結構中找到最適合的視圖,呼叫它的 touches 方法來處理。

觸摸事件的傳遞方向是從父控件到子控件:如果父控件無法接收觸摸事件,子控件就不可能接收到。

如何找到最適合的控件?流程如下:

  1. 判斷自己是否能接收觸摸事件;
  2. 判斷觸摸點是否落在自己身上;
  3. 從後往前遍歷子控件,對每個子控件重複上述兩個步驟;
  4. 若都沒有符合條件的子控件,則由自己處理。

對應的 API 是 hitTest:withEvent:(尋找最適合的 view)與 pointInside:withEvent:(判斷點是否在控件上)。hitTest: 的底層邏輯大致如下:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    // 無法接收觸摸事件的情況直接回傳 nil
    if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) {
        return nil;
    }

    // 觸摸點不在自己身上
    if ([self pointInside:point withEvent:event] == NO) {
        return nil;
    }

    // 從後往前遍歷子控件
    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;
        }
    }

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

四、手勢識別器 UIGestureRecognizer

用 touches 系列方法監聽觸摸事件有個明顯缺點:想要自定義行為往往必須自己繼承 view。因此從 iOS 3.2 起,Apple 推出了手勢識別功能。UIGestureRecognizer 是抽象類別,真正處理具體手勢的是它的各個子類:

UITapGestureRecognizer          點按手勢
UILongPressGestureRecognizer    長按手勢(預設會觸發兩次)
UISwipeGestureRecognizer        輕掃手勢(預設方向為向右)
UIRotationGestureRecognizer     旋轉手勢
UIPinchGestureRecognizer        捏合手勢
UIPanGestureRecognizer          拖拽手勢

五、實際運用

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

@implementation ViewController

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

#pragma mark - 手勢代理方法

// 是否允許同時支援多個手勢,預設為 NO
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    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);
    pinch.scale = 1;   // 復位
}

#pragma mark - 拖拽

- (void)setUpPan {
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.imageView addGestureRecognizer:pan];
}

- (void)pan:(UIPanGestureRecognizer *)pan {
    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 = 0、scale = 1、setTranslation:),否則第二次操作時形變會被重複疊加。

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