0

我正在尝试使用单元格上的 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);
      }
}
4

1 回答 1

1

如果您view的实例与您的实例不同,collectionView那么当您打电话时,[gestureRecognizer locationInView:self.view]您会在错误的坐标空间中得到一个点。当您请求索引路径时,这将导致不准确的响应。

所以,你应该使用

[gestureRecognizer locationInView:self.collectionView]
于 2013-09-26T15:41:50.823 回答