Setting background color of a table view cell on iPhone

后端 未结 12 727
孤街浪徒
孤街浪徒 2020-12-02 11:23

I want to achieve the effect where one cell of the table view will have blue background, the next one will have white, the next one will have blue again, and then white and

12条回答
  •  暖寄归人
    2020-12-02 12:05

    The cell.contentView.backgroundColor = [UIColor colorWithRed...] method in lostInTransit's answer works, as long as you do not use the built-in label of a UITableViewCell.

    I found that if you use the built-in label, e.g. by setting cell.text, you end up with a opaque white block under the label and only the two ends of the cell show your desired color.

    I found no way to edit the built-in label so it is non-opaque (you can access it via UILabel* cellLabel = [cell.contentView.subviews objectAtIndex:0]).

    I solved the problem by adding my own custom UILabel. Like this:

    UILabel* cellLabel = [[[UILabel alloc] initWithFrame:cell.frame] autorelease];
    cellLabel.text = @"Test with non-opaque label";
    cellLabel.backgroundColor = [UIColor clearColor];
    cellLabel.opaque = NO;
    
    [cell.contentView addSubview:cellLabel];
    cell.contentView.backgroundColor = [UIColor darkGrayColor];
    

提交回复
热议问题