Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when UITableViewCell goes off the screen

This is an old question, but in case anyone is looking, in iOS6, a new UITableViewDelegate function was introduced that does just this:

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

It does a great job at telling you whenever a cell is removed, however, it is very thorough and thus if you did a reload cell, even the old cell that's being replaced will trigger this delegate function. In my implementation I simply check to see if the indexPath passed is still within the array tableView.indexPathsForVisibleRows. Something like:

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView.indexPathsForVisibleRows indexOfObject:indexPath] == NSNotFound)
    {
        // This indeed is an indexPath no longer visible
        // Do something to this non-visible cell...
    }
}

I think you could use the

- (NSArray *)visibleCells

method for your UITableView. This returns an array of all cells that are visible. You can then mark any data that is "not visible" (i.e. not in this array) in the way you want, such that when you scroll back to it, it has been updated.

Hope that helps


Once UITableViewCell is invisible, it will be removed from UITableView. You may override the method -(void)removeFromSuperView, and do something within the method. At last, do not forget to call [super removeFromSuperView].


The prepareForReuse method on UITableViewCell that Andrey Tarantsov mentions looks good. Putting a couple of NSLogs in there allows you to print out the values of any variables of the cell. Any thoughts as to how this could be set back to the table view controller?


Are you sure a cell going offscreen is exactly what you want to catch? If you want to mark items as read, this does not seem like a proper way to do it. For example, I might scroll though the table really fast, and I would be very surprised if you marked all of the stuff as read.

As for the technical part, simply keep a list of cells that are on screen (cellForRowAtIndexPath should add cells to that list), and in scrollViewDidScroll delegate method check if any of them are no longer visible.

Another possible idea: I remember there is prepareForReuse method on the cell. Not sure when it is called, though.


I know this is a REALLY old question, but in case anyone is looking for an answer for Swift 5:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    <#code#>
}