Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect swiping in UICollectionView

I need to perform a specific action when the user swipes the uicollectionview. I built it in a way that each cell captures the full screen.

I tried those ways:

A. scrollViewDidEndDecelerating

# pragma UIScrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"detecting scroll");
    for (UICollectionViewCell *cell in [_servingTimesCollectionView visibleCells]) {
        NSIndexPath *indexPath = [_servingTimesCollectionView indexPathForCell:cell];
        CGPoint scrollVelocity = [scrollView.panGestureRecognizer velocityInView:_servingTimesCollectionView];
        if (scrollVelocity.x > 0.0f)
            NSLog(@"going right");
        else if (scrollVelocity.x < 0.0f)
            NSLog(@"going left");
    }
}

But the scrollVelocity returns null. The method is being called.

B. UISwipeGestureRecognizer

In ViewDidLoad of my UIViewController which delegates to UICollectionViewDataSource and UIGestureRecognizerDelegate I added:

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeRight:)];
swipeRight.numberOfTouchesRequired = 1;
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLeft:)];
swipeRight.numberOfTouchesRequired = 1;
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

[_servingTimesCollectionView addGestureRecognizer:swipeRight];
[_servingTimesCollectionView addGestureRecognizer:swipeLeft];

and the followings in the UiViewController:

#pragma mark - UISwipeGestureRecognizer Action
-(void)didSwipeRight: (UISwipeGestureRecognizer*) recognizer {
    NSLog(@"Swiped Right");
}

-(void)didSwipeLeft: (UISwipeGestureRecognizer*) recognizer {
    NSLog(@"Swiped Left");
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer     shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    NSLog(@"Asking permission");
    return YES;
}

But none are called.

What is wrong? I am developing for ios7

like image 945
Dejell Avatar asked Oct 07 '13 18:10

Dejell


1 Answers

You are not setting the delegate of the gestures:

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeRight:)];
    swipeRight.delegate = self;
    swipeRight.numberOfTouchesRequired = 1;
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLeft:)];
    swipeLeft.delegate = self;
    swipeLeft.numberOfTouchesRequired = 1;
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
like image 156
Roberto Ferraz Avatar answered Oct 19 '22 23:10

Roberto Ferraz