触摸事件以及手势
由于博主本人比较懒,学习过程中也做了印象笔记,所以以后博客的内容将直接复制印象笔记中的内容,排版会有些奇怪,博主一般做笔记的习惯是直接在XCode上直接打然后截图在印象笔记上所以会有很多图片,以后博客内容每周更新整理一次,会尽力将博主这礼拜所学东西都上传的。
手势简单来说就是我们创建一个手势然后由UIView来添加,这样子UIView就可以根据你的手势来执行手势的方法,具体的来看代码实现
点按
UITapGestureRecognizer *aTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeColor;)]; aTap.numberOfTapsRequired=2;//点击若干次数才执行事件 aTap.numberOfTouchesRequired=2;//点击的手指数 [self .view addGestureRecognizer:aTap];//让self.view 添加了这个事件之后这个视图只要点击了点按就要实现changecolor得事件
长按
UILongPressGestureRecognizer *aLong=[[UILongPressGestureRecognizer alloc]initWithTarget:self action :@selector(执行事件:)]; aLong.minimumPressDuration=2;//至少长按2秒 aLong.allowableMovement=50;//在出发手势之前,手指可以移动的范围(在这个范围内,依然可以出发长按事件) [self.view addGestureRecognizer: aLong];
轻扫
UISwipeGestureRecognizer *aSwipe=[[UISwipeGestureRecognizer alloc]initWithTargrt:self action:selector( 执行事件:)]; aSwipe.direction=UISwipeGestureRecognizerDirectionleft|UISwipeGestureRecognizerDirectionRight;//轻扫左边或者右边,注意不能同时有轻扫左右和上下 也就是说不能既有扫左又扫上 self.view addGestureRecognizer:aSwipe];
捏合
UIPinchGestureRecognizer *aPinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchImageView:)];//最后不要忘了还要添加
旋转
UIRotationGestureRecognizer *aRotate = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotateImageView:)];
拖拽
UIPanGestureRecognizer *aPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panImageView:)];
[self.imageView addGestureRecognizer:aPan];
手势也有代理方法
@interface ViewController ()<UIGestureRecognizerDelegate>
//某一块区域点击
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
/**
* 是否允许多个手势事件执行
*/
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
清除手势
self.view removeGestureRecognizer:<#(nonnull UIGestureRecognizer *)#>
如果一个view 添加了多个手势,要一个个的清除,他们在View里面是以数组的形式,如博主的某个例子
-(void)removeGR
{
for (UIGestureRecognizer *gestureR in self.imageView.gestureRecognizers) {
[self.imageView removeGestureRecognizer:gestureR];
}
}
触摸事件
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//获取点击屏幕时的touch对象
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:touch.view];//这2步就可以得到触摸的这个点
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event