IOS中各种手势操作实例代码

2020-01-18 22:01:59王冬梅

先看下效果

ios,手势操作

手势相关的介绍

IOS中手势操作一般是 UIGestureRecognizer 类的几个手势子类去实现,一般我们用到的手势就这么5种:

1、点击  UITapGestureRecognizer

2、平移  UIPanGestureRecognizer

3、缩放  UIPinchGestureRecognizer

4、旋转  UIRotationGestureRecognizer

5、轻扫  UISwipeGestureRecognizer

我们上面这个实例中就用到了上面这5种手势,不过其中 点击与轻扫没有体现出来,只是输出了下日志而已,一会看代码

下面我们来分别介绍下这几种手势

1、UITapGestureRecognizer 点击手势


UITapGestureRecognizer* tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGes:)];
// 点击次数,默认为1,1为单击,2为双击
tapGes.numberOfTapsRequired = 2;

这个点击手势类有一个属性 numberOfTapsRequired 用于设置点击数,就是点击几次才触发这个事件

2、UIPanGestureRecognizer 平移手势


// 平移手势
- (void)initPanGes{
 UIPanGestureRecognizer* panGes = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGes:)];
 [self.imgView addGestureRecognizer:panGes];
}
- (void)panGes:(UIPanGestureRecognizer*)ges{
 // 获取平移的坐标点
 CGPoint transPoint = [ges translationInView:self.imgView];
}

平移手势本身没太多可设置的属性,在平移事件触发手,可以用  translationInView 方法获取当前平移坐标点

3、UIPinchGestureRecognizer 缩放手势


// 缩放手势
- (void)initPinGes{
 UIPinchGestureRecognizer* pinGes = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinGes:)];
 [self.imgView addGestureRecognizer:pinGes];
}
- (void)pinGes:(UIPinchGestureRecognizer*)ges{
 // 缩放
 self.imgView.transform = CGAffineTransformScale(self.imgView.transform, ges.scale, ges.scale);
}

缩放手势在事件里面可以获取 scale 属性,表示当前缩放值

4、UIRotationGestureRecognizer 旋转手势


// 旋转手势
- (void)initRotation{
 UIRotationGestureRecognizer* rotationGes = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotationGes:)];
 [self.imgView addGestureRecognizer:rotationGes];
}
- (void)rotationGes:(UIRotationGestureRecognizer*)ges{
 // 旋转图片
 self.imgView.transform = CGAffineTransformRotate(self.imgView.transform, ges.rotation);
}

旋转手势在事件里面可以通过获取 rotation 属性获取当前旋转的角度

5、UISwipeGestureRecognizer 轻扫手势


// 轻扫手势
- (void)initSwipeGes{
 // 创建 从右向左 轻扫的手势
 UISwipeGestureRecognizer* swipeLeftGes = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGes:)];
 // 方向,默认是从左往右
 // 最多只能开启一个手势,如果要开启多个就得创建多个手势
 // 监听从右向左的方向
 swipeLeftGes.direction = UISwipeGestureRecognizerDirectionLeft;
 [self.imgView addGestureRecognizer:swipeLeftGes];
}
- (void)swipeGes:(UISwipeGestureRecognizer*)ges{
 // ges.direction方向值
 NSLog(@"%s diection:%lu",__func__,(unsigned long)ges.direction);
}