views:

231

answers:

2

Hi!

I'm trying to set the label backgroundColor of my UITableViewCells and it does absolutely nothing at all. I wonder if there's another way of doing this, so I'm asking!

I tried this:

    cell.textLabel.backgroundColor = [UIColor redColor];
cell.backgroundColor = [UIColor redColor];

And it doesn't work, anything else?

Thanks!

+12  A: 

I assume you are trying this in cellForRowAtIndexPath.

According to the UITableViewCell class reference:

Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source.

So do this:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.textColor = [UIColor yellowColor]; //can do here OR in cellForRowAtIndexPath
}

If you need finer control over the cell display, an easy way is to design it in IB and load it from the nib in cellForRowAtIndexPath. See the "Loading Custom Table-View Cells From Nib Files" section on this page in the Table View Programming Guide.

DyingCactus
A: 

I had a look at this.

What I don't manage is to actually change the backgroundColor of my UITextField to red

I tried

cell.textField.backgroundColor = [UIColor redColor];

in (a) willDisplayCell (b) cellForRowAtIndexPath

but it only slightly frames the field instead of solid filling it.

Any clues why?

iFloh
You need to ask this as a new question and not as an answer. In the question, include how you are adding "textField" to the cell since default cell does not have a textField property. Also make sure you're adding the UITextField to cell.contentView.
DyingCactus
Set the text field's borderStyle to something OTHER than UITextBorderStyleRoundedRect if you want the background color to fill the field.
DyingCactus