Dawninest

Objective-C | 手势触摸

手势

建立手势对象

1
2
3
4
5
6
7
_animationView = [[UIView alloc]init];
_animationView.bounds = CGRectMake(0, 0, 200, 200);
_animationView.center = self.view.center;
_animationView.backgroundColor = [UIColor colorWithRed:0.21 green:0.6 blue:0.93 alpha:1];
[self.view addSubview:_animationView];
//打开用户交互 如果是imageView,则需要打开交互
_animationView.userInteractionEnabled = YES;

单击手势

1
2
3
4
1.初始化手势控制器-单击手势控制器
UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAnimationView:)];
2.为视图添加手势
[_animationView addGestureRecognizer:tapGes];

缩放手势

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
UIPinchGestureRecognizer *pinchGes = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchAnimationView:)];
[_animationView addGestureRecognizer:pinchGes];
缩放事件
- (void)pinchAnimationView:(UIPinchGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateChanged) {
/*
UIGestureRecognizerStateBegan 开始-开始点击
UIGestureRecognizerStateChanged 改变-每一次移动手指
UIGestureRecognizerStateEnded 结束-手指挪开
*/
CGAffineTransformScale变幻效果的叠加的
当手势改变时执行缩放操作
gesture.view.transform = CGAffineTransformScale(gesture.view.transform, gesture.scale, gesture.scale);
保存缩放系数为1
gesture.scale = 1;
}
}

拖动手势

1
2
3
4
5
6
7
8
9
10
11
12
13
14
UIPanGestureRecognizer *panGes = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAnimationView:)];
[_animationView addGestureRecognizer:panGes];
拖动事件
- (void)panAnimationView:(UIPanGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateChanged) {
获取手指在指定视图(self.view)的移动坐标
CGPoint transition = [gesture translationInView:self.view];
更新 _animationView 的center
gesture.view.center = CGPointMake(gesture.view.center.x + transition.x, gesture.view.center.y + transition.y);
把增量设置为0
[gesture setTranslation:CGPointZero inView:self.view];
}
}

触摸

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
触摸针对的是整个View,是视图控制器自带方法,用的时候直接重写
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
//拿到当前点击位置 通过UITouch
UITouch *nowTouch = touches.anyObject;
CGPoint location = [nowTouch locationInView:self.view];
//弹性动画
//usingSpringWithDamping 阻尼系数 0-1 越小越明显
//initialSpringVelocity 初始速度
[UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:0 animations:^{
//更新图片坐标-加动画
_imageView.bounds = CGRectMake(0, 0, 120, 120);
_imageView.center = location;
} completion:^(BOOL finished){
[UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:0 animations:^{
_imageView.bounds = CGRectMake(0, 0, 80, 80);
} completion:nil];
}];
}