How to customize the background color of the standard label within a UITableViewCell?

StackOverflow https://stackoverflow.com/questions/403820

  •  03-07-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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];

OTHER TIPS

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!

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

How to customize the background color of a UITableViewCell?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top