Determine if a tableview cell is visible

Viewed 62981

Is there any way to know if a tableview cell is currently visible? I have a tableview whose first cell(0) is a uisearchbar. If a search is not active, then hide cell 0 via an offset. When the table only has a few rows, the row 0 is visible. How to determine if row 0 is visible or is the top row?

9 Answers

Another solution (which can also be used to check if a row is fully visible) would be to check if the frame for the row is inside the visible rect of the tableview.

In the following code, ip represents the NSIndexPath:

CGRect cellFrame = [tableView rectForRowAtIndexPath:ip];
if (cellFrame.origin.y<tableView.contentOffset.y) { // the row is above visible rect
  [tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
else if(cellFrame.origin.y+cellFrame.size.height>tableView.contentOffset.y+tableView.frame.size.height-tableView.contentInset.top-tableView.contentInset.bottom){ // the row is below visible rect
  [tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}

Also using cellForRowAtIndexPath: should work, since it returns a nil object if the row is not visible:

if([tableView cellForRowAtIndexPath:ip]==nil){
  // row is not visible
}

Swift:

Improved @Emil answer

extension UITableView {
    
    func isCellVisible(indexPath: IndexPath) -> Bool {
        guard let indexes = self.indexPathsForVisibleRows else {
            return false
        }
        return indexes.contains(indexPath)
    }
}

Best to check by Frame

let rectOfCellInSuperview = yourTblView.convert(yourCell.frame, to: yourTblView.superview!) //make sure your tableview has Superview
if !yourTblView.frame.contains(rectOfCellInSuperview) {
       //Your cell is not visible
}
Related