2010-03-31 55 views
10

如何設置動態生成的標籤邊框(不是來自Interface Builder)?在iphone中設置標籤邊框

+3

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

+0

可能重複的可能重複[如何在UILabel上繪製邊框?](https://stackoverflow.com/questions/2311591/how-to-draw-border-around-a-uilabel) – Suragch 2017-06-10 00:14:45

回答

29

您可以通過

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

做這個之前,你需要導入一個框架QuartzCore/QuartzCore.h

0

我不確定你可以在默認情況下使用UILabel。您可能需要考慮使用只讀(field.editing = NO)UITextField並將其設置爲borderStyle(可使用UITextBorderStyle以編程方式完成)。雖然這可能有點「沉重」。另一個選項可能是子類UILabel繪製您的邊框。

或者,根據您的需要,這可能會更好,使用支持CALayer並使用它的borderColor和borderWidth屬性繪製邊框。

1

您也可以嘗試繼承您的標籤並重寫drawRect:方法繪製或邊框或任何你喜歡的:

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

斯威夫特版本

enter image description here

設置標籤邊框

label.layer.borderWidth = 2.0 

設置邊框顏色

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

使用圓角

label.layer.cornerRadius = 8 

製作背景顏色留圓角內

label.layer.masksToBounds = true