UISwipeGestureRecognizer not working

后端 未结 3 719
星月不相逢
星月不相逢 2021-01-07 13:37

I have a UIView inside of a UIScrollView, both created using IB. The UIView scrolls horizontally inside the UIScrollView. I want to detect left and right 2 finger swipes.

3条回答
  •  终归单人心
    2021-01-07 14:16

    I had the same problem and I solved by using UIPanGestureRecognizer instead of UISwipeGestureRecognizer.

    To emulate the detection of swipe, we'll play with the speed of gesture in scrollview. If the speed of x direction >= 3000 (for example) the swipe will be detected.

    If x>0 it will be a right swipe.

    The code I implemented to resolve your situation is: In a uiscrollview named _scroll1:

    UIPanGestureRecognizer *pan;
    pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(Swipe4ScrollViews:)];
    [pan setMinimumNumberOfTouches:2];
    [_scroll1 addGestureRecognizer:pan];
    [pan release];
    

    With a global BOOL variable named _panning, Swipe4ScrollViews will do the hard job:

    -(void)Swipe4ScrollViews:(UIPanGestureRecognizer *)sender 
    {
        if(sender.state == UIGestureRecognizerStateBegan) _panning = NO;
    
        CGPoint v =[sender velocityInView:_scroll1];
    
        NSLog(@"%f, %f",v.x,v.y);
    
        if( (abs(v.x) >= UMBRAL) && !_panning)
        {
            _panning = YES;
            [sender cancelsTouchesInView];
    
            if(v.x>0) NSLog(@"Right");
            else NSLog(@"Left");
    
            [self doSomething];
        }
    }
    

    I encapsulated it on a UIGestureRecognizer subclass: UISwipe4ScrollGestureRecognizer

提交回复
热议问题