使用自定义手势处理器-陈鹏

  在用户使用给一个或多个手指在屏幕上水平摆动的过程中,程序可用过FKSwingGesture-Recognizer检测到用户的这种摆动手势.

  使用FKSwingGestureRecognizer处理摆动时候的步骤和使用其他手势处理器的步骤完全相同,FKSwingGestureRecognizer定义了如下属性来设置该手势处理器的相关信息.

  >swingCount:设置改拖动手势处理器要求用户手指至少摆动几次.

  下面示例将会示范使用FKSwingGestureRecognizer处理摆动手势,下面是改控制器的实现代码.

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.gv.layer.borderWidth = 2;
    self.gv.layer.cornerRadius = 6;
    // 设置gv控件支持用户交互
    self.gv.userInteractionEnabled = YES;
    // 设置gv控件支持多点触碰
    self.gv.multipleTouchEnabled = YES;
    // 创建手势处理器,指定使用该控制器的handleSwing:方法处理手势
    FKSwingGestureRecognizer* gesture = [[FKSwingGestureRecognizer alloc]
        initWithTarget:self action:@selector(handleSwing:)];
    // 设置该点击手势处理器只处理2个手指的摆动事件
    gesture.swingCount = 2;
    // 为gv控件添加手势处理器。
    [self.gv addGestureRecognizer:gesture];
}
// 实现手势处理器的方法,该方法应该声明一个形参。
// 当该方法被激发时,手势处理器会作为参数传给该方法的参数。
- (void) handleSwing:(FKSwingGestureRecognizer*)gesture
{
    NSUInteger touchNum = gesture.numberOfTouches;
    self.label.text = [NSString stringWithFormat:
        @"用户使用%d个手指进行摆动" , touchNum];
    // 指定2秒后清除label的文本
    [self.label performSelector:@selector(setText:)
        withObject:@"" afterDelay:2];
}

  

  下面是自定义手势处理器:

  

@implementation FKSwingGestureRecognizer
// 记录起始点的Y坐标
CGFloat baseY;
CGFloat prevX;
NSInteger count;
NSUInteger prevDir; // 定义手势移动方向,1代表向右,2代表向左
- (void) touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
{
    [super touchesBegan:touches withEvent:event];
    // 获取多个触碰点中任意一个触碰点
    UITouch* touch = [touches anyObject];
    // 获取触碰点在self.view中的坐标
    CGPoint point = [touch locationInView:self.view];
    baseY = point.y;
    prevX = point.x;
    count = 0;
    prevDir = 0;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    UITouch* touch = [touches anyObject];
    CGPoint currPoint = [touch locationInView:self.view];
    // 如果垂直方向上移动距离过大,则取消手势
    if(fabs(currPoint.y - baseY) > 10)
    {
        self.state = UIGestureRecognizerStateCancelled;
        return;
    }
    NSUInteger currDir = currPoint.x > prevX ? 1 : 2;
    // 刚开始还没有初始化方向时
    if(prevDir == 0)
    {
        prevDir = currDir;
    }
    // 如果前一次的移动方向与当前移动方向不同,可也将“摆动”次数加1
    if(prevDir != currDir)
    {
        // 将“摆动”次数加1
        count++;
        // 使用prevDir记录当前的摆动方向
        prevDir = currDir;
    }
    // 如果改变方向的次数超过了该手势处理器要求的次数,即可判断手势成功
    if(count >= self.swingCount)
    {
        self.state = UIGestureRecognizerStateEnded;
    }
}
原文地址:https://www.cnblogs.com/sixindev/p/4602297.html