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

前端 未结 2 1577
南笙
南笙 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:25

    One way to do it would be to add a UILongPressGestureRecognizer to each UITableViewCell (that all use the same selector), then when the selector is called you can get the cell via sender.view. Perhaps not the most memory efficient, but if the single gesture recognizer won't return the right row in certain situations, this way should work.

    Something like this:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        ...
    
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] 
      initWithTarget:self action:@selector(handleLongPress:)];
        [longPress setMinimumPressDuration:2.0];
        [cell addGestureRecognizer:longPress];
        [longPress release];
    
        return cell;
    }
    

    then

    - (void)handleLongPress:(UILongPressGestureRecognizer*)sender {  
        UITableViewCell *selectedCell = sender.view;
    }
    
    0 讨论(0)
  • 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...!

    0 讨论(0)
提交回复
热议问题