08-手勢識別(點按,長按,輕掃)
通過touches方法監聽view觸摸事件有以下幾個缺點
1.必須得自定義view,在自定義的View當中去實現touches方法.
2.由于是在view內部的touches方法中監聽觸摸事件,因此默認情況下,無法讓其他外界對象監聽view的觸摸事件
3.不容易區分用戶的具體手勢行為(不容易區分是長按手勢,還是縮放手勢)這些等.
iOS 3.2之后,蘋果推出了手勢識別功能(Gesture Recognizer在觸摸事件處理方面大大簡化了開發者的開發難度
UIGestureRecognizer手勢識別器
利用UIGestureRecognizer,能輕松識別用戶在某個view上面做的一些常見手勢
UIGestureRecognizer是一個抽象類,定義了所有手勢的基本行為,使用它的子類才能處理具體的手勢
注意手勢有以下幾種:
UITapGestureRecognizer(敲擊)
UIPinchGestureRecognizer(捏合,用于縮放)
UIPanGestureRecognizer(拖拽)
UISwipeGestureRecognizer(輕掃)
UIRotationGestureRecognizer(旋轉)
UILongPressGestureRecognizer(長按)
手勢使用方法:
1.創建手勢
2.添加手勢
3.實現手勢方法
1.添加點按手勢
創建手勢
Target:當哪對象要堅聽手勢
action:手勢發生時調用的方法
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tap)];
手勢也可以設置代理
tap.delegate = self;
添加手勢
[self.imageV addGestureRecognizer:tap];
以下為手勢代理方法:
是否允許接收手指.
當返回為yes的時候,表示能夠接收手指,當為No的時候,表示不能夠接收手指,也就是不能夠接收事件.
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:
(UITouch *)touch{
獲取當前手指所在的點
CGPoint curP = [touch locationInView:self.imageV];
if (curP.x > self.imageV.bounds.size.width * 0.5) {
在右邊,返回NO
return NO;
}else{
在左邊,返回yes,
return YES;
}
}
當手指開始點擊時調用
-(void)tap{
NSLog(@"%s",__func__);
}
2.添加長按手勢
UILongPressGestureRecognizer *longP = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(longPress:)];
添加手勢
[self.imageV addGestureRecognizer:longP];
當手指長按時調用
注意,長按手勢會調用多次,當開始長按時會調用,當長按松開時會調用,當長按移動時, 也會調用.
一般我們都是在長按剛開始時做事情,所以要判斷它的狀態.
這個狀態是保存的當前的手勢當中, 所以要把當前的長按手勢傳進來, 來判斷當前手勢的狀態.
- (void)longPress:(UILongPressGestureRecognizer *)longP{
手勢的狀態是一個枚舉UIGestureRecognizerState,可以進入頭文件當中查看.
if (longP.state == UIGestureRecognizerStateBegan) {
NSLog(@"開始長按時調用");
}else if(longP.state == UIGestureRecognizerStateChanged){
會持續調用
NSLog(@"當長按拖動時調用");
}else if(longP.state == UIGestureRecognizerStateEnded){
NSLog(@"當長按松手指松開進調用");
}
}
3.輕掃手勢
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(swipe:)];
注意:輕掃手勢默認輕掃的方向是往右輕掃,可以去手動修改輕掃的方向
一個手勢只能對象一個方向,想要支持多個方向的輕掃,要添加多個輕掃手勢
swipe.direction = UISwipeGestureRecognizerDirectionLeft;
添加手勢
[self.imageV addGestureRecognizer:swipe];
再添加一個輕掃手勢
輕掃手勢
UISwipeGestureRecognizer *swipe2 = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(swipe:)];
注意:輕掃手勢默認輕掃的方向是往右輕掃,可以去手動修改輕掃的方向
一個手勢只能對象一個方向,想要支持多個方向的輕掃,要添加多個輕掃手勢
swipe2.direction = UISwipeGestureRecognizerDirectionDown;
添加手勢
[self.imageV addGestureRecognizer:swipe2];