为 iPhone 应用设置 UILabel 透明背景

21

我在UITableView中有一个UILabel。下面是我在cellForRowAtIndexPath中编写的代码。

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(30.0, 5.0, 250.0, 35.0) reuseIdentifier:CellIdentifier] autorelease];
    }   


    CGRect rect = CGRectMake(30.0, 5.0, 250.0, 35.0);
    UILabel *label = [[UILabel alloc] initWithFrame:rect];

    label.opaque = NO;  
    label.font = [UIFont systemFontOfSize:14];
    label.numberOfLines = 2;
    label.textAlignment = UITextAlignmentCenter;            
    label.textColor = [UIColor darkGrayColor];
    label.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
    [label setText:@"Test Message"];    

    [cell addSubview:label];
    [label release];
    cell.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;    

我想将单元格和UILabel的背景设置为透明。

但是它并没有起作用。有人能告诉我我错过了什么吗?

谢谢

Sandeep

3个回答

74
更改以下代码行:
label.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];

变成这样:

label.backgroundColor = [UIColor clearColor];

既然你已经指出了正确的方向(谢谢!),我想补充一下,label.backgroundColor = nil; 更容易记住,并且具有相同的功能。(BG color是UIView超类的属性。根据类参考,“默认值为nil,这会导致背景色透明。”UILabel子类可能最初将其设置为白色,这就是为什么您必须显式将其更改为nil / clear的原因。) - Wienke
1
经过测试,然而,最好还是坚持oden的原始答案。一开始将backgroundColor设置为null是可以的,但如果随后更改标签的文本,新文本将叠加在旧文本上。非常奇怪。 - Wienke
将值设置为nil是我的第一个猜测,但它导致整个标签(文本和背景)变成了完全黑色。[UIColor clearColor]则完美地解决了这个问题。 - Greg Brown
对于 Swift 2.3,请使用 label.backgroundColor = UIColor.clearColor() - Xaren

2

对于使用Xamarin.iOS的人来说,这显然是:

UILabel myLabel = new UILabel();
myLabel.Text = "Hello world!";
myLabel.BackgroundColor = UIColor.Clear;

1
[label setBackGroundColor:[UIColor clearColor]];
设置标签的clearBackGround颜色。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接