Check if a specific UITableViewCell is visible in a UITableView

29,890

Solution 1

Note that you can as well use indexPathsForVisibleRows this way:

    NSUInteger index = [_people indexOfObject:person];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    if ([self.tableView.indexPathsForVisibleRows containsObject:indexPath]) {
      [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
                            withRowAnimation:UITableViewRowAnimationFade];
    }

If you have the indexPath (and don't need the actual Cell) it might be cheaper.

PS: _people is the NSArray used as my backend in this case.

Solution 2

if ([tableView.visibleCells containsObject:myCell])
{
    // Do your thing
}

This assumes that you have a separate instance variable containing the cell you are interested in, I think you do from the question but it isn't clear.

Solution 3

You can use the UITableView method:

[tableView indexPathForCell:aCell];

If the cell doesn't exist in the tableView it will return nil. Otherwise you will get the cell's NSIndexPath.

Solution 4

Since iOS 7, indexPathForVisibleRows will contain a row that is under the translucent navigation bar hence you now need to do this:

[self.tableView indexPathsForRowsInRect:self.tableView.safeAreaLayoutGuide.layoutFrame]

Solution 5

You can do this in Swift 3 to check if the UITableViewCell is visible:

let indexPathToVerify = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPathToVerify)

if tableView.visibleCells.contains(cell) {
    // the cell is visible
}
Share:
29,890

Related videos on Youtube

ozking
Author by

ozking

Updated on July 22, 2022

Comments

  • ozking
    ozking almost 2 years

    I have a UITableView and some UITableViewCells which i have created manually via the Interface Builder. I've assigned each cell an outlet, and im connecting them to the UITableView in the CellForRowAtIndexPath method. In this method, I use the switch(case) method to make specific cells appear in the UITableView, depends on the case.

    Now, I want to find a specific cell and check if he is exists within the UITableView. I use the method: UITableView.visibleCells to get an array of the cells in the table view. My question is - how can i check if a specific cells exists in the array? can I use the outlet that i've assigned to it somehow? - (The best solution),OR, can I use an identifier and how?

    Thanks :)

  • ozking
    ozking over 12 years
    Thanks, it's another way of implementing the solution that Sorig gave me :)
  • Envil
    Envil almost 11 years
    This solution is better than the accepted solution in most cases.
  • Martin Schultz
    Martin Schultz over 9 years
    This is the correct answer to the original question, if a cell is visible. Thanks for the clean and simple answer.