UIImageView 與 UILabel 的 userInteractionEnabled 預設是 NO,也就是說你把任何手勢掛上去都不會有反應。這是新手最常卡住的地方,記得先設為 YES。
self.imageView.userInteractionEnabled = YES;
所有 UIGestureRecognizer 子類的套路一致:初始化時傳入 target 與 action,設定各自的參數,然後用 addGestureRecognizer: 掛到目標視圖上。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]; tap.numberOfTapsRequired = 2; // 點擊幾下才觸發 tap.numberOfTouchesRequired = 2; // 幾根手指同時點 [self.imageView addGestureRecognizer:tap]; [tap release];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)]; longPress.minimumPressDuration = 2; // 最少按住幾秒 longPress.allowableMovement = 200; // 允許手指移動的距離 [self.imageView addGestureRecognizer:longPress]; [longPress release];
長按的 callback 會被連續呼叫多次,實務上通常會判斷 longPress.state 只在特定狀態下才做事,避免同一動作觸發好幾次。
核心概念是透過 view 的 transform 累積旋轉量,而手勢本身的 rotation 是「相對變化值」,用完必須歸零,否則下一幀會疊加出錯。
- (void)rotationAction:(UIRotationGestureRecognizer *)rotation {
UIImageView *imageView = (UIImageView *)rotation.view;
imageView.transform = CGAffineTransformRotate(imageView.transform, rotation.rotation);
rotation.rotation = 0;
}
- (void)pinchAction:(UIPinchGestureRecognizer *)pinch {
UIImageView *imageView = (UIImageView *)pinch.view;
imageView.transform = CGAffineTransformScale(imageView.transform, pinch.scale, pinch.scale);
pinch.scale = 1; // 同樣要歸零
}
拖拽的關鍵是 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];
}
掃動可以指定方向,上下左右各需建立一個實例,並透過 direction 屬性區分。
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)]; swipe.direction = UISwipeGestureRecognizerDirectionUp; [self.imageView addGestureRecognizer:swipe];
同一個 action 若被多個視圖共用,可以透過 recognizer 的 view 屬性反查是哪個視圖觸發的,省去寫好幾份幾乎一樣的 callback。
此外,iOS 7 之後提供了 UIScreenEdgePanGestureRecognizer,專門偵測從螢幕邊緣啟動的拖拽,常用來實作側滑返回或側邊選單。