標籤:style io ar os sp for strong on log
IOS觸摸事件和手勢識別
目錄
概述
為了實現一些新的需求,我們常常需要給IOS添加觸摸事件和手勢識別
觸摸事件
觸摸事件的四種方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 開始觸摸所觸發的方法
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 移動時觸發的方法
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 離開時觸發的方法
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event 系統由於某原因取消觸摸事件時所調用的方法
獲得觸摸位置的方法
for(UITouch *t in touches){
CGPoint touchPosition = [t locationInView:self.view];
NSLog(@"%f,%f",touchPosition.x,touchPosition.y);
}
手勢識別
手勢種類
UITapGestureRecognizer輕觸
UISwipeGestureRecognizer很快的滑動
UIPanGestureRecognizer拖動
UIPinchGestureRecognizer兩個手指頭捏或放
UIRotationGestureRecognizer手指方向操作
UILongPressGestureRecognizer長按
UITapGestureRecognizer輕觸
初始化
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
[view addGestureRecognizer:tapGR];
常用方法
[self setNumberOfTapsRequired:numbers];
[self setNumberOfTouchesRequired:number2];
其他方法可以參考UIGestureRecognizer文檔
UITapGestureRecognizer的回應程式法
-(void)tapAction:(UITapGestureRecognizer *)sender{
//Tap拿起的時候
if(tapGR.state == UIGestureRecognizerStateEnded){
}
//Tap按下的時候
if(tapGR.state == UIGestureRecognizerStateBegan){
}
//等等其他狀態
}
獲得UITapGestureRecognizer按下的位置
CGPoint point = [sender locationInView:view];
IOS觸摸事件和手勢識別