手勢識別是 iOS 開發中不可或缺的一部分。本文系統整理 iOS 中六種常見手勢識別器的用法,並示範如何以 Storyboard 與純程式碼兩種方式為控件添加手勢。
iOS 共提供六種手勢識別器:輕擊手勢(UITapGestureRecognizer)、輕掃手勢(UISwipeGestureRecognizer)、長按手勢(UILongPressGestureRecognizer)、拖動手勢(UIPanGestureRecognizer)、捏合手勢(UIPinchGestureRecognizer)與旋轉手勢(UIRotationGestureRecognizer)。其實這些手勢用 touch 事件都能實現,蘋果只是把常用的觸摸事件封裝成手勢,方便開發者使用。
用 Storyboard 添加手勢的步驟和添加 Button 一樣:先找到對應的手勢識別控件,把它拖到要添加手勢的控件上,再為手勢連線回呼事件,在回呼方法中撰寫業務邏輯即可。這種方式能大幅簡化操作。
純程式碼方式更為靈活、便於維護。實務上建議用 Storyboard 搭好架構(如 Controller 間的關係),零碎的細節再用純程式碼敲出,兩者搭配能大大提升開發效率。
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
tapGesture.numberOfTapsRequired = 1; // 點擊次數
tapGesture.numberOfTouchesRequired = 1; // 點擊手指數
[self.view addGestureRecognizer:tapGesture];UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
longPressGesture.minimumPressDuration = 0.5; // 長按時間
[self.view addGestureRecognizer:longPressGesture];手勢的常用狀態包括:開始(UIGestureRecognizerStateBegan)、改變(Changed)、結束(Ended)、取消(Cancelled)與失敗(Failed)。在回呼中可判斷 state 以決定行為,例如長按開始時彈出提示。
初始化時需指定方向(上下左右)。若要支援多個方向,需添加多個手勢,但它們可以回呼同一個方法:
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; // 默認向右
[self.view addGestureRecognizer:swipeGesture];在回呼方法中可透過 swipe.direction 判斷是向左還是向右輕掃,分別處理。
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
[self.view addGestureRecognizer:pinchGesture];在回呼中可透過 gesture.scale 取得縮放比例,常用於放大或縮小圖片;手勢結束後可用動畫恢復形變。
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self.view addGestureRecognizer:panGesture];可透過 translationInView: 取得移動的座標點,用法與 touchesMoved 類似。
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGesture:)];
[self.view addGestureRecognizer:rotationGesture];可透過 gesture.rotation 取得旋轉角度來完成一系列操作,結束後同樣可用動畫取消形變。
以上就是 iOS 六種手勢識別器的基礎用法總結,希望能幫助大家溫故知新。