UICollectionViewCell的

UICollectionViewCell的

我正在尝试使用Cell上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);
      }
}

最佳答案

如果viewcollectionView不在同一个实例中,则在调用[gestureRecognizer locationInView:self.view]时会在错误的坐标空间中得到一个点。当您请求索引路径时,这将导致响应不正确。

所以,你应该使用

[gestureRecognizer locationInView:self.collectionView]

关于ios - 使用部分的UICollectionView中的LongPressGesture检索UICollectionViewCell的NSIndexPath,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19032287/

10-09 07:05