2012-01-16 99 views
2

嗯,我在UILabel中繪製邊框時遇到了一些問題。這裏是我的代碼在UILabel中繪製邊框

CGRect frame = CGRectMake(10, 10, 320, 120); 
UILabel *label = [[UILabel alloc] initWithFrame:frame]; 
label.textColor = [UIColor greenColor]; 
label.font = [UIFont fontWithName:@"Verdana" size:12]; 
label.textAlignment = UITextAlignmentCenter; 
label.text = @"Some text to display"; 
label.layer.backgroundColor = [UIColor cyanColor].CGColor; 
label.layer.borderColor = [UIColor redColor].CGColor; 
[self.window addSubview:label]; 
[label release];label=nil; 

我有QuartzCore包括和我使用的iOS4.3當我啓動在sumulator文本應用程序顯示,但不是邊框和背景顏色的片段。 這裏有什麼問題?

回答

8

查看CALayer.h,我們看到borderWidth的默認值爲0.0。

/* The width of the layer's border, inset from the layer bounds. The 
* border is composited above the layer's content and sublayers and 
* includes the effects of the `cornerRadius' property. Defaults to 
* zero. Animatable. */ 

@property CGFloat borderWidth; 

爲了邊境出現,你必須設置borderWidth的東西大於零。

您可以設置背景顏色在標籤上直接像這樣:

label.backgroundColor = [UIColor cyanColor]; 

要設置一個邊界,你需要設置寬度,可以像這樣做:

label.layer.borderWidth = 2.0f; 

一旦設置了邊框寬度,設置標籤邊框的顏色,就可以設置視圖的圖層邊框,該邊框使用CGColor,因此您必須這樣做:

label.layer.borderColor = [UIColor redColor].CGColor; 

如果你想圓的角落,你可以補充一點:

label.layer.cornerRadius = 10.0f; 

你並不需要設置背景顏色。你真的只需要設置borderWidth和borderColor。

+0

有趣。我正在做一些我不想出現邊框的地方。我在標籤周圍出現一個微弱的邊框。我的佈局是這樣的:兩個UILabels放置在背景顏色爲白色的UIView中。這個UIView本身就是具有紅色背景的較大UIView的子視圖。微弱的輪廓顯得灰色。 – 2013-01-04 02:08:40

7
label.layer.borderColor = [UIColor darkGrayColor].CGColor; 
label.layer.borderWidth = 1.0;