28

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 :)

5 Answers 5

77

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.

1
  • 3
    This solution is better than the accepted solution in most cases.
    – Envil
    Commented Jul 19, 2013 at 10:09
19
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.

2
  • Thanks, it's another way of implementing the solution that Sorig gave me :)
    – ozking
    Commented Nov 8, 2011 at 16:10
  • This is the correct answer to the original question, if a cell is visible. Thanks for the clean and simple answer. Commented Jan 7, 2015 at 13:14
11

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.

0
1

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]
1

You can do this in Swift 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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.