在iphone中设置标签边框

问题描述:

如何设置动态生成的标签边框(不是来自Interface Builder)?在iphone中设置标签边框

+3

的http://*.com/questions/2311591/how-to-draw-border-around-a-uilabel – Vladimir 2010-03-31 10:12:06

+0

可能重复的可能重复[如何在UILabel上绘制边框?](https://*.com/questions/2311591/how-to-draw-border-around-a-uilabel) – Suragch 2017-06-10 00:14:45

您可以通过

Label.layer.borderColor = [UIColor whiteColor].CGColor; 
Label.layer.borderWidth = 4.0; 

做这个之前,你需要导入一个框架QuartzCore/QuartzCore.h

我不确定你可以在默认情况下使用UILabel。您可能需要考虑使用只读(field.editing = NO)UITextField并将其设置为borderStyle(可使用UITextBorderStyle以编程方式完成)。虽然这可能有点“沉重”。另一个选项可能是子类UILabel绘制您的边框。

或者,根据您的需要,这可能会更好,使用支持CALayer并使用它的borderColor和borderWidth属性绘制边框。

您也可以尝试继承您的标签并重写drawRect:方法绘制或边框或任何你喜欢的:

- (void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [[UIColor blackColor] setStroke]; 
    CGContextStrokeRect(context, self.bounds); 
} 

斯威夫特版本

enter image description here

设置标签边框

label.layer.borderWidth = 2.0 

设置边框颜色

label.layer.borderColor = UIColor.blueColor().CGColor 

使用圆角

label.layer.cornerRadius = 8 

制作背景颜色留圆角内

label.layer.masksToBounds = true