Abraham Vegh Abraham Vegh - 1 year ago 67
iOS Question

How can I send a message to the currently selected table cell after it has moved off-screen?

Here’s my scenario:

I’m showing a

in a
, and I’m drawing the cells myself in a subclass. In order to keep the cells looking as close to possible like native cells, I have a flag that indicates whether it is in a transitional state or not, in order to prevent the text color from visibly flashing when the user moves back up the stack from a detail view to the table view.

Currently, I set my transitioning flag in
, like so:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
// (stuff for pushing the detail view on to the navigation stack)

((MyCustomTableViewCell *) [self.tableView cellForRowAtIndexPath: indexPath]).transitioning = YES;

This works rather well, with one caveat: Immediately before the list animates off-screen, the transition is clearly visible to anyone looking for it, as the cell text changes to black (on blue) from white (on blue.)

My question: Is there any way to get the currently selected cell from the table view, after it has transitioned off-screen, and send it a message? (assuming it isn’t being deallocated, simply unloaded)

Or am I simply going about this whole thing the wrong way?

(For anyone considering saying that nobody will notice it, keep in mind that it’s acceptable to me the way that it is, I’m simply wondering if there’s a way for me to make it better. Good iOS applications are all about the little things.)

Answer Source

UITableView does not keep a publicly-accessible list of all the cells in the table.
In order to access all the cells (including ones out of the screen) you need to maintain a separate array of the cells you generate.

@interface MyViewController : UIViewController 
   NSMutableArray* tableCells;

@implementation MyViewController

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    if (tableCells == nil)
      tableCells = [[NSMutableArray alloc] init];

    UITableViewCell* cell;
    if (indexPath.row < [tableCells count])
        // Return a cell from the cached list
        cell = (UITableViewCell*)[tableCells objectAtIndex:indexPath.row];
        // Create a new cell
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:@"identifier"];  

        // Customize and fill the cell with content anyway you wish
        // ...

    return cell;

Now that you have a list of all the cells in the table, you can send them any message, anytime you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download