【问题标题】:iOS Why can't the method collectionView:didSelectItemAtIndexPath: be called from UITapGestureRecognizer?iOS 为什么不能从 UITapGestureRecognizer 调用方法 collectionView:didSelectItemAtIndexPath:?
【发布时间】:2014-01-23 06:12:48
【问题描述】:

我已经为 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
}

【问题讨论】:

    标签: ios objective-c uiscrollview uicollectionview uitapgesturerecognizer


    【解决方案1】:

    你写的代码,

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

    选择器通常只是一个带有一个输入参数的单个函数,即UITapGestureRecogniser 对象。

    应该是这样的,

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

    但是您使用的选择器不正确,因为它需要两个输入,而手势识别器无法提供。因此崩溃。

    将上面的代码更改为以下代码,

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

    【讨论】:

      【解决方案2】:

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

      - (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:

      【讨论】:

        【解决方案3】:

        我们必须从正确的引用对象中调用 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];
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-02
          • 2015-08-14
          • 2015-07-08
          • 1970-01-01
          • 2011-12-09
          • 2013-07-09
          相关资源
          最近更新 更多