简体   繁体   中英

Retrieve NSIndexPath of UICollectionViewCell with LongPressGesture in UICollectionView with section

i'm trying to retrieve the NSIndexPath of UICollectionViewCell using the UILongPressGestureRecognizer on a UIImageView on the Cell, sometimes works, exactly for the first item of the collection view, but when i scroll the UICollectionView, and i press on a cell retrieve me the first item of the UICollectionViewCell and not what i pressed, and in other case return nil, how i can do to fix this? this is the code:

-(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);
      }
}

If your view isn't the same instance as your collectionView then when you call [gestureRecognizer locationInView:self.view] you are getting a point in the wrong coordinate space. This will result in an inaccurate response when you ask for the index path.

So, you should be using

[gestureRecognizer locationInView:self.collectionView]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM