How can I customize the background color of a standard label in a UITableViewCell?

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

I'm trying to customize the background color of the standard UILabel that comes with the UITableViewCell (since I've already set the background color of the cell itself), but nothing seems to work.

I am creating my own UILabel for customizing 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 as a result, the table view still has a bunch of label cells with black text and white background.

Any hints on what I am doing wrong here?

UPDATE: if I try to do the following:

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 am getting a bunch of UITableViewCells with no text.

0


source to share


3 answers


It seems that you are assigning text to a cell instead of a label. You probably want:

label.text = @"Sample text here";

      

Also, you need to set the label frame according to what you need:



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

      

or directly in the constructor:

label = [[UILabel alloc] initWithFrame:myFrame];

      

+1


source


I would not do this in code. I would do it with a custom XIB file and then upload it to

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

      



delegate function. This way, you can design the XIB file for your specific specifications and customize it.

Good luck!

0


source


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

How can I customize the background color in UITableViewCell?

0


source







All Articles