iOS 为啥不能从 UITapGestureRecognizer 调用方法 collectionView:didSelectItemAtIndexPath:?
Posted
技术标签:
【中文标题】iOS 为啥不能从 UITapGestureRecognizer 调用方法 collectionView:didSelectItemAtIndexPath:?【英文标题】: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
【问题讨论】:
【参考方案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];
【讨论】:
以上是关于iOS 为啥不能从 UITapGestureRecognizer 调用方法 collectionView:didSelectItemAtIndexPath:?的主要内容,如果未能解决你的问题,请参考以下文章
为啥我不能从我自己的 iOS 应用程序将图片上传到我粘贴的事件?
为啥我不能在 iOS 中 RemoveAllObjects 的 NSMutableArray?