在uiscrollview中滑动无法正常工作

时间:2014-03-15 16:24:35

标签: ios uiscrollview swipe

我有UISrollView名为templateView。我必须添加一个滑动手势,以允许用户向左/向右滑动以查看其他模板。问题在于,大多数时候用户无法轻松滑动,因为视图向下/向上滚动而不是滑动到另一个视图。他的手指需要严格水平对齐以滑动到另一页,从用户体验的角度来看,这是不可接受的。

知道如何处理此类案件吗?有没有办法实现一个角度来检测滑动手势?或者,有没有办法将其作为自定义的uigesture来检测具有特定角度的斜线?

提前致谢。

1 个答案:

答案 0 :(得分:4)

尝试实现UIGestureRecognizer Delegate方法。当通过gestureRecognizer或otherGestureRecognizer识别手势将阻止其他手势识别器识别其手势时,调用此方法。请注意,保证返回YES以允许同时识别。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
    shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer  
    {
        return YES;
    }

参考: UIGestureRecognizer Protocol

初始化滑动手势时,不要忘记分配代理。

更新1 创建自己的手势

您始终可以继承UIGestureRecognizer类并实施touchesBegantouchesMovedtouchesEnded方法 - 根据您自己的需要手动管理手势的状态。

我发布了一些实现自定义EdgeGestureRecognizer的示例代码,以便您更好地理解。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = touches.anyObject;
    CGPoint location = [touches.anyObject locationInView:self.view];

    // if not single finger, then fail

    if ([touches count] != 1)
    {
        self.state = UIGestureRecognizerStateFailed;
        return;
    }
   //put here some logics for your case. For instance, you can register
   //here your first touch location, it will help
   //you to calculate the angle after.
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];

    if (self.state == UIGestureRecognizerStateFailed) return;

    UITouch *touch = touches.anyObject;
    self.previousPoint = self.currentPoint;
    self.previousPointTime = self.currentPointTime;
    self.currentPoint = [touch locationInView:self.view];
    self.currentPointTime = touch.timestamp;

    if (self.state == UIGestureRecognizerStatePossible)
    {
        CGPoint translate = CGPointMake(self.currentPoint.x - self.startPoint.x, self.currentPoint.y - self.startPoint.y);

        // see if we've moved the necessary minimum distance

        if (sqrt(translate.x * translate.x + translate.y * translate.y) >= self.minimumRecognitionDistance)
        {
            // recognize if the angle is roughly horizontal, otherwise fail

            double angle = atan2(translate.y, translate.x);

            if ([self isAngleCloseEnough:angle])
                self.state = UIGestureRecognizerStateBegan;
            else
                self.state = UIGestureRecognizerStateFailed;
        }
    }
    else if (self.state == UIGestureRecognizerStateBegan)
    {
        self.state = UIGestureRecognizerStateChanged;
    }
}