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

时间:2014-01-23 06:12:49

标签: ios objective-c uiscrollview uicollectionview uitapgesturerecognizer

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

知道为什么会这样吗?

这有效:

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

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

这不起作用:

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

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

3 个答案:

答案 0 :(得分:5)

你写的代码,

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

选择器通常只是一个带有一个输入参数的singleFunction,它是UITapGestureRecogniser object。

应该是这样的,

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

}

但你使用它的选择器不合适,因为它需要两个输入,不能提供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];

}

答案 1 :(得分:1)

手势识别器的操作必须符合以下签名之一:

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

您需要使用其中一个操作签名,并在该方法中执行您需要的任何操作 ,包括为手势确定正确的indexPath

查看文档: https://developer.apple.com/library/ios/documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html#//apple_ref/occ/instm/UIGestureRecognizer/initWithTarget:action

答案 2 :(得分:0)

我们必须从正确的引用对象调用didSelectItemAtIndexPath。

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

}