ios系統提供了一些常用的手勢(UIgestureRecognizer的子類),方便我們直接使用。
UIGestureRecognizer的繼承關系:
6種手勢中只有UITapGestureRecognizer
是離散型手勢
- 離散型手勢特點:
一旦識別就無法取消,而且只會調用一次手勢操作事件(就是初始化手勢時指定的回調方法)。
- 連續性手勢特點:
另外五種是連續性手勢,他們會多次調用手勢操作事件,而且在連續手勢識別后可以取消手勢。
添加手勢識別的步驟
1.創建手勢識別對象實例
創建時,指定一個回調方法,當手勢開始,改變、或結束時,執行回調方法。
2.設置手勢識別器對象實例的相關屬性
這部分不是必須編寫的。
3.將手勢識別添加到對應的視圖中
每個手勢只對應一個 View,當用戶觸摸的范圍在 View 的邊界內時,如果手勢和預定的一樣,那就會執行回調方法。
點擊手勢TapGestureRecognizer
- 新建tap手勢
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
- 設置點擊次數和點擊手指數
這里可以控制用戶的單擊或者是雙擊
tapGesture.numberOfTapsRequired = 1; //點擊次數
tapGesture.numberOfTouchesRequired = 1; //點擊手指數
- 將手勢添加到對應視圖
[self.view addGestureRecognizer:tapGesture];
- 點擊觸發的方法
-(void)tapGesture:(id)sender
{
//點擊后要做的事情
}
長按手勢LongPressGestureRecognizer
- 新建長按手勢
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
- 設置長按時間
longPressGesture.minimumPressDuration = 0.5; //(2秒)
- 添加長按手勢到對應視圖
[self.view addGestureRecognizer:longPressGesture];
- 長按觸發的方法
-(void)longPressGesture:(id)sender{
//長按后要做的事情
}
輕掃手勢SwipeGestureRecognizer
- 添加輕掃手勢
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
- 設置輕掃的方向
swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //默認向右
- 添加輕掃手勢到對應視圖
[self.view addGestureRecognizer:swipeGesture];
- 輕掃觸發的方法
-(void)swipeGesture:(id)sender{
//輕掃后要做的事情
}
捏合手勢PinchGestureRecognizer
- 添加捏合手勢
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
- 將捏合手勢添加到對應視圖
[self.view addGestureRecognizer:pinchGesture];
- 捏合觸發的方法
-(void)pinchGesture:(id)sender{
//捏合后要做的事
}
拖動手勢PanGestureRecognizer
- 添加拖動手勢
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
- 將拖動手勢添加到對應視圖
[self.view addGestureRecognizer:panGesture];
- 拖動觸發的方法
-(void)panGesture:(id)sender{
//拖動后要做的事
}
旋轉手勢RotationGestureRecognizer
- 添加旋轉手勢
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGesture:)];
- 將旋轉手勢添加到對應視圖
[self.view addGestureRecognizer:rotationGesture];
- 旋轉觸發的方法
-(void)rotationGesture:(id)sender{
//旋轉后要做的事
}