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

iOS 開發中的手勢操作實例詳解

編輯:iOS 開發綜合

手勢是現代行動應用不可或缺的互動方式。本文以「同時識別單擊與雙擊」這個經典難題切入,說明兩種手勢檢測思路,並進一步示範 UIGestureRecognizer 各子類的實際應用。

單擊與雙擊為何會衝突?

當我們在同一個視圖上同時掛載單擊與雙擊手勢時,問題就出現了:系統偵測到一次點擊後,無法立刻判斷這究竟是「一次真正的單擊」,還是「一次雙擊中的第一次點擊」。解決思路是——偵測到單擊時先延遲一小段時間等待第二次點擊,若在時間內沒有第二次點擊就判定為單擊,否則判定為雙擊。

手勢檢測有兩種常見做法:一是自定義子視圖並重寫從 UIResponder 繼承而來的 touchesBegan:withEvent: 等一系列事件處理方法;二是直接使用 UIGestureRecognizer 的各種具體子類。

做法一:重寫事件處理方法

- (id)init {
    if ((self = [super init])) {
        self.userInteractionEnabled = YES;
        self.multipleTouchEnabled = YES;
    }
    return self;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];

    if (touch.tapCount == 1) {
        // 延遲 0.3 秒執行單擊處理,等待可能的第二次點擊
        [self performSelector:@selector(handleSingleTap:)
                   withObject:[NSValue valueWithCGPoint:touchPoint]
                   afterDelay:0.3];
    } else if (touch.tapCount == 2) {
        [self handleDoubleTap:[NSValue valueWithCGPoint:touchPoint]];
    }
}

運作原理如下:第一次觸摸結束時,由於尚未調度任何方法,cancelPreviousPerformRequestsWithTarget: 不會生效,此時 tapCount 為 1,於是排程 0.3 秒後執行單擊處理。若這確實是單擊,0.3 秒內不會再有觸摸事件,handleSingleTap: 便會執行;若這其實是雙擊,第二次點擊會在 0.3 秒內到來,此時 cancelPreviousPerformRequestsWithTarget: 會取消先前排程的單擊方法,改為調用 handleDoubleTap:。別忘了先確認自定義視圖的 userInteractionEnabled 與 multipleTouchEnabled 均為 YES。

做法二:使用 Gesture Recognizer

相較之下,手勢識別器讓實作簡單許多,只需各添加一個單擊與雙擊識別器並設置必要屬性即可:

- (id)init {
    if ((self = [super init])) {
        self.userInteractionEnabled = YES;

        UITapGestureRecognizer *singleTapGesture =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        singleTapGesture.numberOfTapsRequired = 1;
        singleTapGesture.numberOfTouchesRequired = 1;
        [self addGestureRecognizer:singleTapGesture];

        UITapGestureRecognizer *doubleTapGesture =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        doubleTapGesture.numberOfTapsRequired = 2;
        doubleTapGesture.numberOfTouchesRequired = 1;
        [self addGestureRecognizer:doubleTapGesture];

        // 關鍵:只有當雙擊識別失敗時,單擊識別才會啟動
        [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
    }
    return self;
}

最關鍵的一句是 [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];。它的含義是:唯有當 doubleTapGesture 識別失敗(也就是判定這不是雙擊)時,singleTapGesture 才會開始工作——這與前面做法一的思路完全一致。

UIGestureRecognizer 綜合應用

以下示範一個圖片視圖_controller,透過切換按鈕分別演示輕點、長按、平移、旋轉、捏合與輕掃六種手勢:

  • 輕點(雙指單擊):把 imageView 的 frame 改為 (0, 0, 320, 200)
  • 長按(單指):把 imageView 的 alpha 設為 0.5
  • 平移、旋轉、捏合:分別對圖像做位移、旋轉與縮放
  • 輕掃:竖向輕掃隨機切換圖片;横向輕掃讓圖像消失並隨機變換背景色

以下為各手勢的核心實作:

#pragma mark 點擊手勢
- (void)createTapGestureRecognizer {
    _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapGestureRecognizer:)];
    _tapGesture.numberOfTapsRequired = 1;
    _tapGesture.numberOfTouchesRequired = 2;
    [self.imageView addGestureRecognizer:_tapGesture];
}

#pragma mark 長按手勢
- (void)createLongGestureRecognizer {
    _longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGestureRecognizer:)];
    _longGesture.numberOfTouchesRequired = 1;
    _longGesture.minimumPressDuration = 1.0;
    [self.imageView addGestureRecognizer:_longGesture];
}
- (void)longGestureRecognizer:(UILongPressGestureRecognizer *)longGesture {
    self.imageView.alpha = 0.5;
}

#pragma mark 平移手勢
- (void)panGestureRecognizer:(UIPanGestureRecognizer *)panGesture {
    CGPoint txty = [panGesture translationInView:self.view];
    self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, txty.x, txty.y);
    [panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
}

#pragma mark 旋轉手勢
- (void)rotationGestureRecognizer:(UIRotationGestureRecognizer *)rotateGesture {
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, rotateGesture.rotation);
    rotateGesture.rotation = 0;
}

#pragma mark 捏合縮放手勢
- (void)pinchGestureRecognizer:(UIPinchGestureRecognizer *)pinchGesture {
    self.imageView.transform = CGAffineTransformScale(self.imageView.transform, pinchGesture.scale, pinchGesture.scale);
    pinchGesture.scale = 1;
}

#pragma mark 輕掃手勢
- (void)swipeGestureRecognizer:(UISwipeGestureRecognizer *)swipeGesture {
    if (swipeGesture.direction == (UISwipeGestureRecognizerDirectionUp | UISwipeGestureRecognizerDirectionDown)) {
        // 竖向輕掃:隨機切換圖片
        self.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"h%i.jpeg", arc4random() % 7 + 1]];
    } else if (swipeGesture.direction == (UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight)) {
        // 横向輕掃:清空圖像並隨機變換背景色
        self.imageView.image = nil;
        self.imageView.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0
                                                        green:arc4random() % 256 / 255.0
                                                         blue:arc4random() % 256 / 255.0
                                                        alpha:1.0];
    }
}

最後要特別提醒:每個 imageView 一次只能添加一種手勢識別器。範例中的做法是每次點擊按鈕前先調用 resetImageView 移除所有既有手勢,再重新添加對應手勢,同時把 imageView 的 alpha、transform、frame、image 還原到初始狀態,確保切換手勢時畫面乾淨一致。

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