iOS - indexPathForRowAtPoint don't return correct indexPath with different cell height

前端 未结 2 1582
南笙
南笙 2021-01-22 02:38

I have UITableView that contains many cell. User can expand cell to see more content in this cell by push the expand button in this cell (only 1 cell can expand at time):

2条回答
  •  滥情空心
    2021-01-22 03:29

    First add the long press gesture recognizer to the table view:

    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
      initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 2.0; //seconds
    lpgr.delegate = self;
    [self.myTableView addGestureRecognizer:lpgr];
    [lpgr release];
    

    Then in the gesture handler:

    -(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
    {
      if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
      { 
        CGPoint p = [gestureRecognizer locationInView:self.myTableView];
    
        NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p];
        if (indexPath == nil)
            NSLog(@"long press on table view but not on a row");
        else
            NSLog(@"long press on table view at row %d", indexPath.row);
        } 
    }
    

    You have to be careful with this so that it doesn't interfere with the user's normal tapping of the cell and also note that handleLongPress may fire multiple times before user lifts their finger.

    Thanks...!

提交回复
热议问题