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

iOS 手勢識別器全解:點擊、長按、旋轉、捏合、拖拽與掃動

編輯:iOS 開發綜合

動手之前:先打開用戶交互

UIImageView 與 UILabel 的 userInteractionEnabled 預設是 NO,也就是說你把任何手勢掛上去都不會有反應。這是新手最常卡住的地方,記得先設為 YES。

 self.imageView.userInteractionEnabled = YES;

六種手勢的實作方式

所有 UIGestureRecognizer 子類的套路一致:初始化時傳入 target 與 action,設定各自的參數,然後用 addGestureRecognizer: 掛到目標視圖上。

1. 點擊 UITapGestureRecognizer

 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.numberOfTapsRequired = 2;      // 點擊幾下才觸發
tap.numberOfTouchesRequired = 2;   // 幾根手指同時點
[self.imageView addGestureRecognizer:tap];
[tap release];

2. 長按 UILongPressGestureRecognizer

 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
longPress.minimumPressDuration = 2;  // 最少按住幾秒
longPress.allowableMovement = 200;   // 允許手指移動的距離
[self.imageView addGestureRecognizer:longPress];
[longPress release];

長按的 callback 會被連續呼叫多次,實務上通常會判斷 longPress.state 只在特定狀態下才做事,避免同一動作觸發好幾次。

3. 旋轉 UIRotationGestureRecognizer

核心概念是透過 view 的 transform 累積旋轉量,而手勢本身的 rotation 是「相對變化值」,用完必須歸零,否則下一幀會疊加出錯。

 - (void)rotationAction:(UIRotationGestureRecognizer *)rotation {
    UIImageView *imageView = (UIImageView *)rotation.view;
    imageView.transform = CGAffineTransformRotate(imageView.transform, rotation.rotation);
    rotation.rotation = 0;
}

4. 捏合縮放 UIPinchGestureRecognizer

 - (void)pinchAction:(UIPinchGestureRecognizer *)pinch {
    UIImageView *imageView = (UIImageView *)pinch.view;
    imageView.transform = CGAffineTransformScale(imageView.transform, pinch.scale, pinch.scale);
    pinch.scale = 1;   // 同樣要歸零
}

5. 拖拽 UIPanGestureRecognizer

拖拽的關鍵是 translationInView: 取得位移量,並在套用後把手勢的基準點重設為 CGPointZero,否則位移會一直累加。

 - (void)panAction:(UIPanGestureRecognizer *)pan {
    UIImageView *imageView = (UIImageView *)pan.view;
    CGPoint p = [pan translationInView:imageView];
    imageView.transform = CGAffineTransformTranslate(imageView.transform, p.x, p.y);
    [pan setTranslation:CGPointZero inView:imageView];
}

6. 掃動 UISwipeGestureRecognizer

掃動可以指定方向,上下左右各需建立一個實例,並透過 direction 屬性區分。

 UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
swipe.direction = UISwipeGestureRecognizerDirectionUp;
[self.imageView addGestureRecognizer:swipe];

一個實用技巧:用手勢找到視圖

同一個 action 若被多個視圖共用,可以透過 recognizer 的 view 屬性反查是哪個視圖觸發的,省去寫好幾份幾乎一樣的 callback。

此外,iOS 7 之後提供了 UIScreenEdgePanGestureRecognizer,專門偵測從螢幕邊緣啟動的拖拽,常用來實作側滑返回或側邊選單。

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