您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 手勢與手勢響應器 UIGestureRecognizer 詳解

編輯:iOS 相關資訊

手勢響應是 iOS 中處理觸摸交互的重要機制。iOS 封裝了 UIGestureRecognizer 類,能響應各種常見手勢。本文詳細介紹其六個子類與使用流程。

六種基本手勢識別器

1、UITapGestureRecognizer:點擊手勢識別器,可識別單擊或多擊;
2、UIPinchGestureRecognizer:捏合手勢識別器,用於視圖的放大縮小;
3、UIRotationGestureRecognizer:旋轉手勢識別器;
4、UISwipeGestureRecognizer:滑動手勢識別器,可向上、下、左、右滑動;
5、UIPanGestureRecognizer:拖動手勢識別器;
6、UILongPressGestureRecognizer:長按手勢識別器,常見於長按跳出編輯介面。

基本使用流程

1、建立手勢識別器;
2、配置能識別的具體手勢;
3、把手勢識別器添加到視圖中。

一、點擊手勢

// 單擊
UITapGestureRecognizer *pSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleGesture:)];
pSingleTap.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:pSingleTap];

// 雙擊
UITapGestureRecognizer *pDoubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleGesture:)];
pDoubleTap.numberOfTapsRequired = 2;
[self.view addGestureRecognizer:pDoubleTap];

// 讓單擊在雙擊識別失敗時才識別,避免重複響應
[pSingleTap requireGestureRecognizerToFail:pDoubleTap];

最後一行 requireGestureRecognizerToFail: 的作用是:當有一個點擊手勢時,先判斷是否能被 pDoubleTap 識別,若能則不再由 pSingleTap 響應,這樣就避免了雙擊時單擊也被觸發兩次的問題。若再加一個三擊識別器,只需讓雙擊 requireGestureRecognizerToFail: 三擊即可,形成層層遞進的判斷。

二、滑動手勢

UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
swipe.direction = UISwipeGestureRecognizerDirectionLeft; // 一個識別器只能識別一個方向
[self.view addGestureRecognizer:swipe];

三、長按手勢

UILongPressGestureRecognizer *pLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
pLongPress.minimumPressDuration = 2; // 長按多少秒後識別
[self.view addGestureRecognizer:pLongPress];

四、移動手勢

UIPanGestureRecognizer *pPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self.view addGestureRecognizer:pPan];
// 獲取當前移動到的位置
CGPoint point = [pPan locationInView:self.view];

五、捏合手勢

捏合有兩個屬性:velocity(捏合速度)與 scale(比例,默認值為 1,常用於放縮比例)。

UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(doPinch:)];
pinch.delegate = self;
[self.view addGestureRecognizer:pinch];

六、旋轉手勢

旋轉有兩個屬性:rotation(旋轉角度)與 velocity(旋轉速度),主要透過取得旋轉角度來完成操作。

UIRotationGestureRecognizer *rotat = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(doRotate:)];
rotat.delegate = self;
[self.view addGestureRecognizer:rotat];

以上就是六種基本手勢識別器的用法。透過這些識別器,我們可以輕鬆地為視圖加上豐富的觸摸交互能力。

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