我正在尝试使用单元格上的 UIImageView 上的 UILongPressGestureRecognizer 检索 UICollectionViewCell 的 NSIndexPath,有时工作,完全适用于集合视图的第一项,但是当我滚动 UICollectionView 时,我按下一个单元格检索我的第一个UICollectionViewCell 的项目而不是我按下的项目,在其他情况下返回 nil,我该如何解决这个问题?这是代码:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
...
UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPress:)];
longPressRecognizer.minimumPressDuration = 1.0;
[cell.imgView setUserInteractionEnabled:YES];
[cell.imgView addGestureRecognizer:longPressRecognizer];
...
}
-(void)onLongPress:(UILongPressGestureRecognizer*)gestureRecognizer
{
if(UIGestureRecognizerStateBegan == gestureRecognizer.state) {
NSLog(@"began");
NSLog(@"%2.f %.2f",[gestureRecognizer locationInView:self.view].x,[gestureRecognizer locationInView:self.view].y);
NSIndexPath *item = [self.collectionView indexPathForItemAtPoint:[gestureRecognizer locationInView:self.view]];
NSLog(@"%d - %d",item.row,item.section);
MyCell *cell = (MyCell *)[self.collectionView cellForItemAtIndexPath:item];
NSLog(@"%@",cell.myLabel.text);
}
}