How can I set label's border which is dynamically generated (Not from Interface Builder)?
-
3possible duplicate of http://stackoverflow.com/questions/2311591/how-to-draw-border-around-a-uilabel – Vladimir Mar 31 '10 at 10:12
-
Possible duplicate of [How to draw border around a UILabel?](https://stackoverflow.com/questions/2311591/how-to-draw-border-around-a-uilabel) – Suragch Jun 10 '17 at 00:14
4 Answers
you can do it by
Label.layer.borderColor = [UIColor whiteColor].CGColor;
Label.layer.borderWidth = 4.0;
before this you need to import a framework QuartzCore/QuartzCore.h

- 1
- 1

- 13,743
- 3
- 64
- 88
Swift version
Set label border
label.layer.borderWidth = 2.0
Set border color
label.layer.borderColor = UIColor.blueColor().CGColor
Use rounded corners
label.layer.cornerRadius = 8
Make background color stay within rounded corners
label.layer.masksToBounds = true

- 484,302
- 314
- 1,365
- 1,393
You can also try to subclass your label and override the drawRect: method to draw or a border or whatever you like:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor blackColor] setStroke];
CGContextStrokeRect(context, self.bounds);
}

- 4,213
- 1
- 21
- 14
I'm not sure you can by default with UILabel
. You might want to consider using a read-only (field.editing = NO) UITextField
and setting it's borderStyle (which can be done programmatically using a UITextBorderStyle
). That may be a little 'heavy' though. Another option may be to sub-class UILabel
to draw your border.
Alternatively, and depending on your needs this may be better, use the backing CALayer
and draw a border using it's borderColor and borderWidth properties.

- 701
- 5
- 14

- 5,512
- 2
- 21
- 11