ozking
ozking

Reputation: 448

Check if a specific UITableViewCell is visible in a UITableView

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

Upvotes: 28

Views: 31890

Answers (5)

pableiros
pableiros

Reputation: 16082

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
}

Upvotes: 1

malhal
malhal

Reputation: 30754

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]

Upvotes: 1

StuFF mc
StuFF mc

Reputation: 4169

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.

Upvotes: 77

jrturton
jrturton

Reputation: 119292

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.

Upvotes: 19

Sorig
Sorig

Reputation: 1211

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.

Upvotes: 11

Related Questions