2010-10-29 68 views
3

我潛入iOS開發中,並以編程方式創建一些標籤,但似乎無法將其背景顏色設置爲黑色。從我讀,它看起來很簡單,這裏是我的代碼...如何以編程方式設置UILabel的背景顏色?

UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height] autorelease]; 
[[lbl layer] setBorderColor:[[UIColor blackColor] CGColor]]; 
[[lbl layer] setBorderWidth:1.0]; 
[[lbl layer] setBackgroundColor:[[UIColor blackColor] CGColor]]; 
[[self view] addSubview:lbl]; 

當我做到這一點,如預期的邊框顏色和寬度的工作,但背景顏色保持白色。我忘了做點什麼嗎?

非常感謝您的幫助!

回答

17

一個UILabel已經有一個.backgroundColor屬性,你並不需要調整其層...

lbl.backgroundColor = [UIColor blackColor]; 
+0

謝謝,那工作。你會碰巧知道爲什麼另一種方法不起作用嗎? – BeachRunnerFred 2010-10-29 18:05:03

+0

@Beach:不。可能是標籤的backgroundColor被繪製在圖層上方,因爲您可以通過將標籤的backgroundColor設置爲'[UIColor clearColor]'來顯示圖層的backgroundColor。 – kennytm 2010-10-29 18:18:51

+0

它不起作用,因爲backgroundColor只接受UIColor,而不接受CGColor – honcheng 2011-03-21 00:16:15

1

設置的UILabel的背景顏色

[lbl.backgroundColor:[UIColor colorWithPatternImage:[UIImage  imageNamed:@"color_lightblue.png"]]]; 

與圖像顏色設置的UILabel的TEXTCOLOR

[label_Description setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"color_lightgray.png"]]]; 

簡單背景顏色

lbl.backgroundColor = [UIColor blackColor]; 
0

迅速2

label.backgroundColor = UIColor.whiteColor() 

其它式:

 let label = UILabel(frame: CGRectMake(0, 0, view.frame.width, view.frame.height)) 

     label.backgroundColor = UIColor.whiteColor() 
     label.textAlignment = NSTextAlignment.Center 
     label.text = message 
     label.numberOfLines = 2 
     label.font = UIFont.systemFontOfSize(12) 
0
lbl.backgroundColor = [UIColor blackColor]; 
0

使用此

with one code you can set color

LabelObj.backgroundColor = [UIColor blackColor];

+0

@ kennytm或Prasad Bulbule的回答有什麼不同? – 2017-02-09 09:33:41

相關問題