Question

I've set up a UITapGestureRecognizer for a UIScrollView inside a UICollectionView. I've configured it to properly detect taps and trigger a method I wrote, but if I try to set the selector to collectionView:didSelectItemAtIndexPath: the program crashes when a cell is tapped.

Any idea why this is the case?

This works:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];

- (void) tapped:(UIGestureRecognizer *)gesture{
//some code
}

This does not work:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(collectionView:didSelectItemAtIndexPath:)];

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//some code
}
Was it helpful?

Solution

the code you wrote,

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(collectionView:didSelectItemAtIndexPath:)];

The selector is generally just a singleFunction with one input argument which is UITapGestureRecogniser object.

should be like this,

-(void)clicked:(UIGestureRecogniser *)ges{

}

But the selector you used it improper, because it needs two inputs which cant be supplied with gestureRecogniser.Hence the crash.

Change your above code to below one,

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clicked:)];
-(void)clicked:(UIgestureRecogniser *)ges{
    //use gesture to get get the indexPath, using CGPoint (locationInView). 
    NSIndexPath *indexPath = ...;
    [self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath];

}

OTHER TIPS

The action for a gesture recognizer must conform to one of the following signatures:

- (void)handleGesture;
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;

You need to use one of these action signatures and do whatever you need to in that method , including determining the correct indexPath for the gesture.

See the docs: https://developer.apple.com/library/ios/documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html#//apple_ref/occ/instm/UIGestureRecognizer/initWithTarget:action:

We have to call the didSelectItemAtIndexPath from the proper reference object.

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];

- (void) tapped:(UIGestureRecognizer *)gesture{

      NSIndexPath *indexPath =    //create your custom index path here

      [self.collectionViewObject didSelectItemAtIndexPath:indexPath];

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top