全部繼承自 UIGestureRecognizer:
UITapGestureRecognizer 輕點 UIPinchGestureRecognizer 捏合 UIPanGestureRecognizer 平移(拖動) UISwipeGestureRecognizer 輕掃 UIRotationGestureRecognizer 旋轉 UILongPressGestureRecognizer 長按
建立方式統一為 alloc initWithTarget:action:。
// 1. 單擊
UITapGestureRecognizer *tap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
[imageV addGestureRecognizer:tap];
// 2. 雙擊
UITapGestureRecognizer *doubleTap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction1:)];
doubleTap.numberOfTapsRequired = 2; // 點擊次數
[imageV addGestureRecognizer:doubleTap];
// 關鍵:宣告雙擊優先。指定「只有雙擊失敗時,單擊才算成立」,
// 避免單擊在雙擊之前就先觸發
[tap requireGestureRecognizerToFail:doubleTap];
// 3. 長按
UILongPressGestureRecognizer *longPress =
[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
[imageV addGestureRecognizer:longPress];
// 4. 輕掃
UISwipeGestureRecognizer *swipe =
[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
swipe.direction = UISwipeGestureRecognizerDirectionRight; // 輕掃方向
[imageV addGestureRecognizer:swipe];
// 5. 平移(會持續回呼,適合跟手拖動)
UIPanGestureRecognizer *pan =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[imageV addGestureRecognizer:pan];
// 讓平移與輕掃互斥:輕掃成立則平移失敗
[pan requireGestureRecognizerToFail:swipe];
// 6. 旋轉
UIRotationGestureRecognizer *rotation =
[[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationAction:)];
[imageV addGestureRecognizer:rotation];
// 7. 捏合
UIPinchGestureRecognizer *pinch =
[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
[imageV addGestureRecognizer:pinch];這個方法是多手勢共存的關鍵。它的意思是「當我指定的那個手勢判定失敗時,我才進入待辨識狀態」。上面的兩個例子分別處理了兩種典型衝突:
另一個相關工具是 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: 委派方法。若你希望捏合與旋轉能同時運作(例如讓圖片同時縮放又旋轉),就不能用 require 互斥,而要回傳 YES 允許並行辨識。