dev.nikolaz
dev.nikolaz

Reputation: 3184

How to prevent scrollview in UITableView when user swipe gesture down two touches?

I want when user swipe direction down on UITableView, I do some stuff and table is not scrolling. How I can do this?

Upvotes: 0

Views: 1067

Answers (2)

Nyth
Nyth

Reputation: 582

If you just want your UISwipeGestureRecognizer to fire alongside the UITableView's UIPanGestureRecognizer, you just need to set the delegate of your swipe gesture and implement

- (BOOL) gestureRecognizer:(UIGestureRecognizer *) gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *) otherGestureRecognizer

then return YES.

If you want to interrupt the tableview's pan gesture, you probably can't use UISwipeGestureRecognizer to do so, since it doesn't actually fire until the user has swiped a certain distance.

You can, however, use a UIPanGestureRecognizer to fake that behavior if you need. I was able to get something similar:

#pragma mark UIViewController lifecycle

- (void) viewDidLoad
{
    [super viewDidLoad];

    UIPanGestureRecognizer *panner = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPan:)];
    [panner setDelegate:self];
    [panner setMinimumNumberOfTouches:2];
    [self.tableView addGestureRecognizer:panner];
}

#pragma mark custom swipe response

- (void) didSwipe
{
    NSLog(@"SWIPED!");
}

#pragma mark UIPanGestureRecognizer response

- (void) didPan:(UIPanGestureRecognizer *) recognizer
{
    [self cancelGestureRecognizer:self.tableView.panGestureRecognizer];

    if (recognizer.state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [recognizer translationInView:self.view];

        if (translation.y > 20)
        {
            [self didSwipe];
            [self cancelGestureRecognizer:recognizer];
        }
    }
}

#pragma mark UIGestureRecognzierDelegate implementation
- (BOOL) gestureRecognizer:(UIGestureRecognizer *) gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *) otherGestureRecognizer
{
    //NOTE: blindly returning yes in this case is usually a bad idea. You should check the recognizers here. 
    return YES;
}

#pragma mark UIGestureRecognizer stuff that should be in a category and not this file.

- (void) cancelGestureRecognizer:(UIGestureRecognizer *) recognizer
{
    if (recognizer.enabled)
    {
        [recognizer setEnabled:NO];
        [recognizer setEnabled:YES];
    }
}

That said, in most cases it makes for a far better user experience just to use a pan gesture and make whatever animation/transition/interaction based on the distance they've panned (that's the CGPoint translation in this case).

Upvotes: 3

michaelsnowden
michaelsnowden

Reputation: 6192

Try this:

self.tableView.panGestureRecognizer.maximumNumberOfTouches = 1;

Upvotes: 0

Related Questions