views:

826

answers:

1

In all of my UITableView programming, I've always configured my UITableViewCells in -[UITableViewDataSource tableView:cellForRowAtIndexPath:]. Now I've come across the -[UITableViewDelegate willDisplayCell:forRowAtIndexPath:] method. That also seems like an appropriate place to do cell configuration.

My question is: what's the appropriate "division of labor" between these two methods? What should I do in one vs. the other?

Thanks.

+5  A: 

You use that to configure things like font and text color. In the newer version of the iPhone, with certain table configurations, if you configure things like the label text color in the tableView:cellForRowAtIndexPath: method, your changes will be lost at some point before the cell is actually displayed. Here you can do things like change the label's color, adjust background highlighting, such things as these.

Jason Coco
Thanks. Is there a rationale for why changes to cells made in tableView:cellForRowAtIndexPath: might get "lost"? I'm wondering where that boundary is between things that get lost and things that won't.
Greg Maletic
None that I know of. I didn't even know that this existed either until suddenly a bunch of label changes stopped working when we built for the 3.0 SDK (and even then, only in very specific table configurations). When we bugged this, we got back "works as intended: use willDisplayCell:forRowAtIndexPath: for this. No other explanation was ever provided ;)
Jason Coco
Actually, thinking more on it, you are probably supposed to do display-related things here and content related/cell initialization things in the other.
Jason Coco
What I'm thinking: why not just put cell creation/dequeueing in cellForRowAtIndexPath, then everything else in willDisplayCell:? I simply haven't run into any problems doing it the old-fashioned way, but I may shift to this model in the future.
Greg Maletic
One thing that definitely fails unless done in willDisplayCell:forRowAtIndexPath: is the backgroundColor property on either the textLabel or the detailedTextLabel. If you set those in your cellForRowAtIndexPath: method, the property will be reset to the tableView's background color before actually being displayed (but even then, only in standard table views).
Jason Coco
Good to know. Thanks.
Greg Maletic
Not to belabor the point, but it makes complete sense to keep view-related details out of the data source delegate... that's why it's a separate delegate! Let it worry about your model, let the view delegate worry about the view. As your app scales up, you ideally want to be left well positioned to externalize the data source delegate to a new class (and if you have the habit of intermingling it, it might be best to separate them from the start).
Justin Searls