Getting the exact location of a UITableViewCell

后端 未结 9 577
滥情空心
滥情空心 2021-01-30 20:10

Given a UITableView, how can I find the location of a specific UITableViewCell? In other words, I want to get its frame relative to my iPhone screen, n

相关标签:
9条回答
  • 2021-01-30 20:58

    Jhaliya's answer wasn't quite enough for me, I needed to do some more manipulations to get it working. My tableView was added to a viewController and its location on the right half way down the screen. So you need to take the tableView origin into account aswel as the scroll offset.

    CGRect rowRect = [tableView rectForRowAtIndexPath:indexPath];
    CGPoint offsetPoint = [self.infoTableView contentOffset];
    
    // remove the offset from the rowRect
    rowRect.origin.y -= offsetPoint.y;
    
    // Move to the actual position of the tableView
    rowRect.origin.x += self.infoTableView.frame.origin.x;
    rowRect.origin.y += self.infoTableView.frame.origin.y;
    
    0 讨论(0)
  • 2021-01-30 21:01

    Swift 3

    Relative to the tableView:

    let rect = self.tableView.rectForRow(at: indexPath)
    

    Relative to the Screen:

    If you only know the cell,

    if let indexPath = tableView.indexPath(for: cell) {
         let rect = self.tableView.rectForRow(at: indexPath)
         let rectInScreen = self.tableView.convert(rect, to: tableView.superview)
    }
    

    If you know the indexPath then don't need call the if statement.

    0 讨论(0)
  • 2021-01-30 21:08

    Apart from rectForRowAtIndexPath you need to consider the scrolling.

    Try this code:

     // Get the cell rect and adjust it to consider scroll offset
     CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
     cellRect = CGRectOffset(cellRect, -tableView.contentOffset.x, -tableView.contentOffset.y);
    
    0 讨论(0)
提交回复
热议问题