1.手勢的分類
UITapGestureRecognizer :點擊手勢(根據設定單擊次數可以分爲單次點擊和多次點擊)
UIPinchGestureRecognizer :縮放或捏合手勢
UIPanGestureRecognizer :平移或拖拽手勢
UISwipeGestureRecognizer :輕掃手勢
UIRotationGestureRecognizer :旋轉手勢
UILongPressGestureRecognizer :長按手勢
2.手勢的基本使用
(1)以單擊手勢爲例,先初始化手勢
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tapGestureAction:)];
第一個參數是綁定手勢觸發時通知的對象,第二個參數是手勢觸發時執行的方法
(2)設置手勢的屬性
例如在第一步的基礎上,將點擊手勢設置爲雙擊手勢
tapGesture.numberOfTapsRequired = 2;
(3)添加手勢
[view addGestureRecognizer:tapGesture];
(4)編輯手勢觸發方法
在tapGestureAction:裏編輯你想要的操作
3.幾個手勢的具體使用
(1)輕掃手勢的使用
- (void)showGestureForSwipeRecognizer:(UISwipeGestureRecognizer *)recognizer { |
// 得到點擊的位置 |
CGPoint location = [recognizer locationInView:self.view]; |
// 判斷手勢的方向,根據方向移動位置 |
if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) { |
location.x -= 220.0; |
} else { |
location.x += 220.0; |
} |
// 實現動畫 |
[UIView animateWithDuration:0.5 animations:^{ |
self.imageView.alpha = 0.0; |
self.imageView.center = location; |
}]; |
} |
(2)旋轉手勢的簡單使用
- (void)showGestureForRotationRecognizer:(UIRotationGestureRecognizer *)recognizer { |
// 得到點擊的位置 |
CGPoint location = [recognizer locationInView:self.view]; |
// 讓圖片跟着手勢一起旋轉 |
CGAffineTransform transform = CGAffineTransformMakeRotation([recognizer rotation]); |
self.imageView.transform = transform; |
// 實現取消手勢的動畫 |
if (([recognizer state] == UIGestureRecognizerStateEnded) || ([recognizer state] == UIGestureRecognizerStateCancelled)) { |
[UIView animateWithDuration:0.5 animations:^{ |
self.imageView.alpha = 0.0; |
self.imageView.transform = CGAffineTransformIdentity; |
}]; |
} }
|
4.手勢衝突問題
(1)如果想要輕掃手勢的識別優先於拖拽手勢,可以使用下面這句話,這句話的意思是只有在識別輕掃手勢失敗時纔會識別拖拽手勢,如果識別輕掃手勢成功就不會繼續 識· 別託轉手勢
[self.panRecognizer requireGestureRecognizerToFail:self.swipeRecognizer];
(2)如何禁止某個視圖識別一個手勢
- (void)viewDidLoad { |
[super viewDidLoad]; |
// 首先設置手勢的代理對象 |
self.tapGestureRecognizer.delegate = self; |
} |
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
// 判斷是否點擊在某個視圖或者姿勢圖上 |
if ([touch view] == self.customSubview){ |
// 如果不想讓這個視圖成功識別這個手勢和以返回NO |
return NO; |
} |
return YES; |
} |