触摸
视图响应触摸的三个时间阶段的方法
触摸开始的方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
触摸移动的方法
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
触摸结束的方法
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
获取触摸在屏幕上的手指对象
UITouch *touch = [touches anyObject];
获取手指之前在屏幕上的位置
CGPoint previousP = [touch previousLocationInView:self];
获取手指现在在屏幕上的位置
CGPoint currentP = [touch locationInView:self];
响应者链
触摸检测查询 先UIApplication -> window -> viewController -> view -> 触摸的子视图
事件处理的顺序与触摸检测查询顺序相反,如果没有响应者处理事件,触摸事件则会被丢弃
关闭用户交互则会阻断响应者链,无法完成检测
默认关闭用户交互的空间有 UILabel 和 UIImageView
开启用户交互:imageView . userInteractionEnabled = YES;
手势
以imageView为例
①.创建满足需求的手势,再创建时关联手势触发时的方法
tip:创建手势的代码:[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
②.配置手势的相关属性
③.将手势添加到需要执行操作的视图上面
tip:添加手势的代码:[imageView addGestureRecognizer:tap];
④.实现手势方法,当触摸发生,手势识别器识别到相对应的触摸时,就会执行关联方法
tip:关联手势的代码:[UIImageView *imageView = (UIImageView *)longPress.view]; //返回值为UIView 所以要进行类型强转
轻拍手势 UITapGestureRecognizer
包含的属性:
1.触发手势的手指个数 tap.numberOfTouchesRequired = 1;
2.触发手势的轻拍次数 tap.numberOfTapsRequired = 2;
轻扫手势 UISwipeGestureRecognizer
包含的属性:指定轻扫的方向 swipe.direction = UISwipeGestureRecognizerDirectionUP/Down/Left/Right
可以同时指定方向相反的两个方向,中间用 | 隔开;
长按手势 UILongPressGestureRecognizer
包含的属性:长按手势触发的最短时间,默认是0.5秒 longPress.minimumPressDuration = 3.0;
缩放手势UIPinchGestureRecognizer
旋转手势 UIRotationGestureRecognizer
平移手势 UIPanGestureRecognizer
这三个手势无属性 但是相关联的方法中要改变视图的transform相关的值
缩放实现方法:
- (void)pinchAction:(UIPinchGestureRecognizer *)pinch {
UIImageView *imageView = (UIImageView *)pinch.view;
imageView.transform = CGAffineTransformScale(imageView.transform, pinch.scale. pinch.scale);
pinch.scale = 1;//重定义改变比例,防止改变比例会累加而导致变化过快
}
旋转实现方法:
- (void)rotateAction:(UIRotationGestureRecognizer *)rotate {
UIImageView *imageView = (UIImageView *)rotate.view;
imageView.transform = CGAffineTransformRotate(imageView.transform, rotate.rotation.rotate.rotation);
rotate.rotation= 0;//重定义改变比例,防止改变比例会累加而导致变化过快
}
平移实现方法:
- (void)panAction:(UIPanGestureRecognizer *)pan {
UIImageView *imageView = (UIImageView *)pan.view;
CGPoint p = [pan translationInView:imageView];
imageView.transform = CGAffineTransformTranslate(imageView.transform, p.x. p.y);
[pan setTranslation:CGPointZero inView:imageView];//平移量归零
}
网友评论