tags:

views:

565

answers:

3

I'm trying for the past several hours to figure out how to do this, but with no luck. There are several potential solutions for this when searching Google, but nothing seems to work.

I'm trying to customize the background color of the standard UILabel that goes in a UITableViewCell (since I already customized the background color of the cell itself), but nothing I do seems to work.

I'm creating my own UILabel to customize the colors in -tableView:cellForRowAtIndexPath:

UILabel* label = [[[UILabel alloc] init] autorelease];
label.textColor = [UIColor blueColor];
label.backgroundColor = [UIColor redColor];
label.opaque = YES;
[cell.contentView addSubview:label];
cell.text = @"Sample text here";

But that doesn't work, and the resulting table view still has a bunch of cells with labels with black text and white background in it.

Any clues on what I am doing wrong here?

UPDATE: If I try to do the following instead:

UILabel* label = [[[UILabel alloc] init] autorelease];
label.textColor = [UIColor blueColor];
label.backgroundColor = [UIColor redColor];
label.opaque = YES;
[cell.contentView addSubview:label];
label.text = @"Sample text here";

I get a bunch of UITableViewCells with no text at all.

+1  A: 

It appears that you're assigning the text to the cell instead of the label. You probably want:

label.text = @"Sample text here";

Also, you'll need to set the label's frame to what you require:

label.frame = CGRectMake(10,10, 80, 40);

or directly in the constructor:

label = [[UILabel alloc] initWithFrame:myFrame];
codelogic
No, that makes the cell show up without any text whatsoever. I will update the question to reflect that.
jpm
You'll also need to set the frame's size. I've updated my answer.
codelogic
Sorry, by frame, I meant label.
codelogic
A: 

I wouldn't do this in code. I would do it with a custom XIB file and then load it in your

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath

delegate function. That way you can design the XIB file to your exact specs, and tweak it.

Good luck!

Genericrich
A: 

You have asked this question before, and received correct answers;

http://stackoverflow.com/questions/281515/how-to-customize-the-background-color-of-a-uitableviewcell

Andrew Grant
No, that was for a different type of customization -- namely, for a grouped-style table view. On this question I simply wanted to change the background color of the UILabel.
jpm