iOS UIGestureRecognizer 自定义手势

自定义一个 左右的摆动手势 ,当用户在屏幕上左右摆动的时候系统就会检测到这个操作,从而做出相应的处理。

1、首先创建一个 继承 UIGestureRecognizer 的子类

2、重写 UIGestureRecognizer 基类触碰相关的几个方法,通过在这些方法中识别用户手指划过的痕迹--当符合要求的时候 state 置为 UIGestureRecognizerStateEnded.

导入 

#import <UIKit/UIGestureRecognizerSubclass.h>

定义一些基本的全局变量

{
    
    CGFloat baseX;//初始X的位置
    CGFloat baseY;//初始Y的位置
    NSInteger swapCount;//滑动的次数
    NSUInteger precDir;//方向 1代表向右,2代表向左
}

接下来重写

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;

这两个方法。

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    NSLog(@"点击开始");
    
    //获取多个触碰点中的任意一个
    UITouch *touch = [touches anyObject];
    //获取点在view中的坐标
    CGPoint point = [touch locationInView:self.view];
    baseX = point.x;
    baseY = point.y;
    swapCount = 0;
    precDir = 0;
    
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [super touchesMoved:touches withEvent:event];
    NSLog(@"移动手势");
    UITouch *touch = [touches anyObject];
    CGPoint currectPoint = [touch locationInView:self.view];
    if (fabs(currectPoint.y - baseY) > 10) {
        self.state = UIGestureRecognizerStateCancelled;
        NSLog(@" 不能在竖直方向移动的距离过大 ");
        return;
    }
    
    NSUInteger currDir = currectPoint.x > baseX ? 1 : 2;//判断移动的方向
    //刚开始还没有初始化方向时
    if (precDir == 0) {
        precDir = currDir;
    }
    
    //如果前一次的移动方向和当前的移动方向不同,则将"摆动"次数加1
    
    if (precDir != currDir) {
        swapCount ++;
        precDir = currDir;
    }
    
    
    if (swapCount >= 2) {
        self.state = UIGestureRecognizerStateEnded;
    }
}

到这里位置,一个简单的自定义摆动手势就完成了,用法和系统的完全一样。

转载于:https://my.oschina.net/onlysimple/blog/729534

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值