iOS为什么不能从UITapGestureRecognizer调用方法collectionView:didSelectItemAtIndexPath?

she*_*eep 0 objective-c uiscrollview ios uitapgesturerecognizer uicollectionview

我在UICollectionView中为UIScrollView设置了一个UITapGestureRecognizer.我已将其配置为正确检测点击并触发我编写的方法,但如果我尝试将选择器设置为collectionView:didSelectItemAtIndexPath:程序在点击单元格时崩溃.

知道为什么会这样吗?

这有效:

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

- (void) tapped:(UIGestureRecognizer *)gesture{
//some code
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

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

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//some code
}
Run Code Online (Sandbox Code Playgroud)

san*_*thu 5

你写的代码,

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(collectionView:didSelectItemAtIndexPath:)];
Run Code Online (Sandbox Code Playgroud)

选择器通常只是一个具有一个输入参数的singleFunction,它是UITapGestureRecogniserobject.

应该是这样的,

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

}
Run Code Online (Sandbox Code Playgroud)

但是你使用它的选择器不合适,因为它需要两个输入,不能提供gestureRecogniser.Hence崩溃.

将上面的代码更改为低于1,

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];

}
Run Code Online (Sandbox Code Playgroud)