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
}
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];
}
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.
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.