在 iOS 里,UIGestureRecognizer
?是一個抽象基類,專門用來處理手勢事件。它本身不能直接用,必須用它的?子類。這些子類分別對應常見的手勢識別器。
常見的?UIGestureRecognizer
?子類及作用
1.?UITapGestureRecognizer
作用:點擊手勢(單擊 / 雙擊)。
典型場景:點擊按鈕外區域關閉鍵盤、圖片點擊放大。
參數:可以設置?
numberOfTapsRequired
(點擊次數)、numberOfTouchesRequired
(手指數)。UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; tap.numberOfTapsRequired = 2; // 雙擊 tap.numberOfTouchesRequired = 1; // 單指 [view addGestureRecognizer:tap];
2.?UILongPressGestureRecognizer
作用:長按手勢。
典型場景:微信長按消息彈出菜單、長按圖片保存。
參數:
minimumPressDuration
(按壓時間,默認 0.5 秒),allowableMovement
(手指允許移動的范圍)。UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 0.8; [view addGestureRecognizer:longPress];
3.?UIPanGestureRecognizer
作用:拖拽手勢(連續)。
典型場景:拖拽視圖移動,滑動解鎖。
方法:
translationInView:
?獲取手指相對位置,velocityInView:
?獲取速度。UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; [view addGestureRecognizer:pan];
4.?UISwipeGestureRecognizer
作用:輕掃手勢(單次)。
典型場景:左右滑動切換頁面。
參數:
direction
(方向,可組合:UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight
)。UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; swipe.direction = UISwipeGestureRecognizerDirectionLeft; [view addGestureRecognizer:swipe];
5.?UIPinchGestureRecognizer
作用:捏合手勢(雙指縮放)。
典型場景:圖片縮放、地圖縮放。
方法:
scale
(縮放倍數),可結合?view.transform
。UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]; [view addGestureRecognizer:pinch];
6.?UIRotationGestureRecognizer
作用:旋轉手勢(雙指旋轉)。
典型場景:圖片旋轉。
方法:
rotation
(旋轉角度,弧度制)。UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)]; [view addGestureRecognizer:rotation];
總結對比
子類 | 作用 | 常用場景 |
---|---|---|
UITapGestureRecognizer | 單擊 / 雙擊 | 點背景關閉鍵盤、點擊放大 |
UILongPressGestureRecognizer | 長按 | 彈出菜單、保存圖片 |
UIPanGestureRecognizer | 拖拽 | 拖動視圖、滑動解鎖 |
UISwipeGestureRecognizer | 輕掃 | 翻頁、滑動刪除 |
UIPinchGestureRecognizer | 捏合縮放 | 圖片/地圖縮放 |
UIRotationGestureRecognizer | 旋轉 | 圖片旋轉 |
額外說明:
手勢沖突處理:可以用?
gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:
?來允許多個手勢并存。UIGestureRecognizer 基類:也提供了手勢狀態(
began / changed / ended / cancelled
),子類里都能用。