08-手勢識別(點按,長按,輕掃)

Make by:弓_雖_子

通過touches方法監聽view觸摸事件的缺點?

1.必須得自定義view,在自定義的View當中去實現touches方法.

2.由于是在view內部的touches方法中監聽觸摸事件,因此默認情況下,無法讓其他外界對象監聽view的觸摸事件

3.不容易區分用戶的具體手勢行為(不容易區分是長按手勢,還是縮放手勢)這些等.

iOS 3.2之后,蘋果推出了手勢識別功能(Gesture Recognizer在觸摸事件處理方面大大簡化了開發者的開發難度

UIGestureRecognizer手勢識別器

利用UIGestureRecognizer,能輕松識別用戶在某個view上面做的一些常見手勢

UIGestureRecognizer是一個抽象類,定義了所有手勢的基本行為,使用它的子類才能處理具體的手勢

手勢使用方法

1.創建手勢

2.添加手勢

3.實現手勢方法

添加點按手勢

UITapGestureRecognizer*tap= [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(tap)];

手勢也可以設置代理

tap.delegate=self;

添加手勢

[self.imageVaddGestureRecognizer:tap];

代理方法:

是否允許接收手指

-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizershouldReceiveTouch:(UITouch*)touch{

讓圖片的左邊不可以點擊,

獲取當前手指所在的點.是在圖片的左邊還是在圖片的右邊.

CGPointcurP = [touchlocationInView:self.imageV];

if(curP.x>self.imageV.bounds.size.width*0.5) {

在圖片的右側

returnYES;

}else{

在圖片的左側

returnNO;

}

returnYES;

}

添加長按手勢

UILongPressGestureRecognizer*longP = [[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(longP:)];

[self.imageVaddGestureRecognizer:longP];

當長按時調用.

這個方法會調用很多次,當手指長按在上面不松,來回移動時,會持續調用.

所以要判斷它的狀態.

- (void)longP:(UILongPressGestureRecognizer*)longP{

if(longP.state==UIGestureRecognizerStateBegan){

NSLog(@"開始長按");

}elseif(longP.state==UIGestureRecognizerStateChanged){

NSLog(@"長按時手指移動");

}elseif(longP.state==UIGestureRecognizerStateEnded){

NSLog(@"手指離開屏幕");

}

}

添加輕掃手勢

UISwipeGestureRecognizer*swipe = [[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(swipe:)];

輕掃手勢默認是向右邊稱輕掃

可以設置輕掃的方法.

一個輕掃手勢只能設置一個方法的輕掃.想要讓它有多個方向的手勢,必須得要設置的

swipe.direction=UISwipeGestureRecognizerDirectionLeft;

[self.imageVaddGestureRecognizer:swipe];

添加輕掃手勢

UISwipeGestureRecognizer*swipe2 = [[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(swipe:)];

輕掃手勢默認是向右邊稱輕掃

可以設置輕掃的方法.

一個輕掃手勢只能設置一個方法的輕掃.想要讓它有多個方向的手勢,必須得要設置的

swipe2.direction=UISwipeGestureRecognizerDirectionUp;

[self.imageVaddGestureRecognizer:swipe2];

- (void)swipe:(UISwipeGestureRecognizer*)swipe{

判斷的輕掃的方向

if(swipe.direction==UISwipeGestureRecognizerDirectionLeft) {

NSLog(@"向左輕掃");

}elseif(swipe.direction==UISwipeGestureRecognizerDirectionUp){

NSLog(@"向上輕掃");

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容