11

How can I set label's border which is dynamically generated (Not from Interface Builder)?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
iOS_User
  • 1,372
  • 5
  • 21
  • 35
  • 3
    possible 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 Answers4

30

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

Community
  • 1
  • 1
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
3

Swift version

enter image description here

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
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
1

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);
}
zonble
  • 4,213
  • 1
  • 21
  • 14
0

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.

Nilesh
  • 701
  • 5
  • 14
dannywartnaby
  • 5,512
  • 2
  • 21
  • 11