2010-02-16 70 views
21

我在UITableView中有一個UILabel。這裏是我寫在cellForRowAtIndexPath的代碼爲iphone應用程序設置UILabel的透明背景

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的背景爲透明。

但它不工作。任何一個可以告訴我什麼,我在這裏失去了

感謝

桑迪普

回答

74

更改以下行:

label.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0]; 

這樣:

label.backgroundColor = [UIColor clearColor]; 
+0

設置clearBackGround顏色現在,你已經指出我們在正確的方向(謝謝!)我要補充的是'label.backgroundColor =零; '更容易記住,做同樣的事情。 (BG顏色是超類UIView的一個屬性,每個類ref,「默認值是nil,這會導致透明的背景顏色。」UILabel子類可能最初將它設置爲白色,這就是爲什麼您必須顯式更改它回到無/清除。) – Wienke 2012-09-27 15:13:06

+1

然而,經過測試,事實證明你應該堅持奧登的原始答案。首先,忽略backgroundColor可以正常工作,但如果隨後更改標籤的文本,則新文本將疊加*在舊的文本上。很奇怪。 – Wienke 2012-09-27 19:50:21

+0

將值設置爲零也是我的第一個猜測,但它導致整個標籤(文本和背景)完全變黑。 [UIColor clearColor]完美運作。 – 2013-05-16 00:45:53

2

對於使用Xamarin那些.iOS很明顯:

UILabel myLabel = new UILabel(); 
myLabel.Text = "Hello world!"; 
myLabel.BackgroundColor = UIColor.Clear; 
1
[label setBackGroundColor:[UIColor clearColor]]; 

要爲標籤