views:

5193

answers:

3

A UITableViewCell comes "pre-built" with a UILabel as its one and only subview after you've init'ed it. I'd really like to change the background color of said label, but no matter what I do the color does not change. The code in question:

UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;

Any hints as to why this doesn't work? Thanks!

+7  A: 

Your code snippet works fine for me, but it must be done after the cell has been added to the table and shown, I believe. If called from the initWithFrame:reuseIdentifier:, you'll get an exception, as the label subview has not yet been created.

Probably the best solution is to add your own UILabel, configured to your standards, rather than relying on this (very rickety) path to the built-in one.

Ben Gottlieb
Well, the reason I ask in the first place is because I want to rely on the rickety path, ie: I don't want to have to create my own subview (yup, I'm that lazy).You say my code works for you in that it changes the background color? Can you be more specific on how you got it working?
rpj
I'm lazy too, but this is dangerous ;-) I added a deferred call in the init method of my cell that called your code. It changed the background color (and text color, of course).
Ben Gottlieb
Ah, I get what you're saying now... and you're right, that seems pretty damn dangerous. Thanks!
rpj
A: 

Add your own label to the contentView when you are allocating the cell, rather than relying on the extraction of the built in one. Then you can control all values:

UILabel* label = [[[UILabel alloc] init] autorelease];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;
[cell.contentView addSubview:label];
Kendall Helmstetter Gelner
This doesn't seem to work at all, at least not from within tableView:cellForRowAtIndexPath: where I'm trying to get things working. Any hints?
rpj