2012-01-16 120 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;