How do I create a round cornered UILabel on the iPhone?
Asked Answered
B

16

154

Is there a built in way to create round-cornered UILabels? If the answer is no, how would one go about creating such an object?

Boride answered 4/2, 2009 at 7:19 Comment(0)
M
235

iOS 3.0 and later

iPhone OS 3.0 and later supports the cornerRadius property on the CALayer class. Every view has a CALayer instance that you can manipulate. This means you can get rounded corners in one line:

view.layer.cornerRadius = 8;

You will need to #import <QuartzCore/QuartzCore.h> and link to the QuartzCore framework to get access to CALayer's headers and properties.

Before iOS 3.0

One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:

  1. Create a UIView subclass and name it something like RoundRectView.
  2. In RoundRectView's drawRect: method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.
  3. Create a UILabel instance and make it a subview of the RoundRectView.
  4. Set the frame of the label to be a few pixels inset of the RoundRectView's bounds. (For example, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.

Moreville answered 4/2, 2009 at 9:22 Comment(3)
view.layer.cornerRadius still draws the entire view (offscreen instead when it's enabled) and only at the CoreAnimation layer will it clip your view. The cost is that it will make putting any view with it enabled in a UIScrollView, kill your scrolling performance.Harewood
Using cornerRadius inside a UIScrollView will kill your scrolling performance? I might believe you if we're talking about a UITableView, but a single rounded-corner view isn't going to grind the view drawing system to a halt.Moreville
If you want to do this in Interface Builder instead of code, you can set a User Defined Runtime Attribute with key path "layer.cornerRadius" in the Identity Inspector.Bigmouth
B
147

For devices with iOS 7.1 or later, you need to add:

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;
Bluebottle answered 4/4, 2014 at 7:54 Comment(1)
Set the corner radius but masksToBounds is slow for scrolling/animation. If you set the layer's background color vs the view that's enough in conjunction with the layer's cornerRadius on 7.1 (where it would have stopped working with only cornerRadius).Winthrop
D
25

For Swift IOS8 onwards based on OScarsWyck answer:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
Decidua answered 17/8, 2015 at 16:8 Comment(3)
Please don't clutter up Stack Overflow with translations of Objective-C answers into Swift, particularly when the only change in this case is changing YES to true.Hannahhannan
The change in this case is minimal, but as a general point translations from Objective-C into Swift are often very useful.Intercalation
How about editing the original answer and adding Swift translation there?Fumble
S
11
  1. you have an UILabel called: myLabel.
  2. in your "m" or "h" file import: #import <QuartzCore/QuartzCore.h>
  3. in your viewDidLoad write this line: self.myLabel.layer.cornerRadius = 8;

    • depends on how you want you can change cornerRadius value from 8 to other number :)

Good luck

Stem answered 4/12, 2012 at 10:8 Comment(0)
D
11

You can make rounded border with width of border of any control in this way:-

CALayer * l1 = [lblName layer];
[l1 setMasksToBounds:YES];
[l1 setCornerRadius:5.0];

// You can even add a border
[l1 setBorderWidth:5.0];
[l1 setBorderColor:[[UIColor darkGrayColor] CGColor]];


Just replace lblName with your UILabel.

Note:- Don't forget to import <QuartzCore/QuartzCore.h>

Digastric answered 13/2, 2014 at 8:9 Comment(0)
D
10

Swift 3

If you want rounded label with background color, in addition to most of the other answers, you need to set layer's background color as well. It does not work when setting view background color.

label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.layer.backgroundColor = UIColor.lightGray.cgColor

If you are using auto layout, want some padding around the label and do not want to set the size of the label manually, you can create UILabel subclass and override intrinsincContentSize property:

class LabelWithPadding: UILabel {
    override var intrinsicContentSize: CGSize {
        let defaultSize = super.intrinsicContentSize
        return CGSize(width: defaultSize.width + 12, height: defaultSize.height + 8)
    }
}

To combine the two you will also need to set label.textAlignment = center, otherwise the text would be left aligned.

Directorial answered 29/5, 2017 at 21:52 Comment(0)
T
9

I made a swift UILabel subclass to achieve this effect. In addition I automatically set the text color to either black or white for maximal contrast.

Result

colors-rounded-borders

Used SO-Posts:

Playground

Just paste this into an iOS Playground:

//: Playground - noun: a place where people can play

import UIKit

class PillLabel : UILabel{

    @IBInspectable var color = UIColor.lightGrayColor()
    @IBInspectable var cornerRadius: CGFloat = 8
    @IBInspectable var labelText: String = "None"
    @IBInspectable var fontSize: CGFloat = 10.5

    // This has to be balanced with the number of spaces prefixed to the text
    let borderWidth: CGFloat = 3

    init(text: String, color: UIColor = UIColor.lightGrayColor()) {
        super.init(frame: CGRectMake(0, 0, 1, 1))
        labelText = text
        self.color = color
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup(){
        // This has to be balanced with the borderWidth property
        text = "  \(labelText)".uppercaseString

        // Credits to https://mcmap.net/q/23596/-how-to-draw-border-around-a-uilabel
        layer.borderWidth = borderWidth
        layer.cornerRadius = cornerRadius
        backgroundColor = color
        layer.borderColor = color.CGColor
        layer.masksToBounds = true
        font = UIFont.boldSystemFontOfSize(fontSize)
        textColor = color.contrastColor
        sizeToFit()

        // Credits to https://mcmap.net/q/23597/-add-a-border-outside-of-a-uiview-instead-of-inside
        frame = CGRectInset(self.frame, -borderWidth, -borderWidth)
    }
}


extension UIColor {
    // Credits to https://mcmap.net/q/23598/-check-if-uicolor-is-dark-or-bright
    func isLight() -> Bool{
        var green: CGFloat = 0.0, red: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
        self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        let brightness = ((red * 299) + (green * 587) + (blue * 114) ) / 1000

        return brightness < 0.5 ? false : true
    }

    var contrastColor: UIColor{
        return self.isLight() ? UIColor.blackColor() : UIColor.whiteColor()
    }
}

var label = PillLabel(text: "yellow", color: .yellowColor())

label = PillLabel(text: "green", color: .greenColor())

label = PillLabel(text: "white", color: .whiteColor())

label = PillLabel(text: "black", color: .blackColor())
Theocritus answered 30/3, 2016 at 14:16 Comment(0)
M
9

If you want rounded corner of UI objects like (UILabel, UIView, UIButton, UIImageView) by storyboard then set clip to bounds true and set User Defined Runtime Attributes Key path as layer.cornerRadius, type = Number and value = 9 (as your requirement)

Set clip to bounds as Set User Defined Runtime Attributes as

Monongahela answered 28/6, 2017 at 10:49 Comment(0)
C
8

xCode 7.3.1 iOS 9.3.2

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;
Celestial answered 21/7, 2016 at 11:22 Comment(0)
A
6

Another method is to place a png behind the UILabel. I have views with several labels that overlay a single background png that has all the artwork for the individual labels.

Antagonist answered 4/2, 2009 at 17:24 Comment(0)
A
5

Works fine in Xcode 8.1.2 with Swift 3

.cornerRadius is the key property to set rounded edges. If you are using the same style for all labels in your application, I would recommend for an extension method.

Code:

 // extension Class
extension UILabel {

    // extension user defined Method
    func setRoundEdge() {
        let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        //Width of border
        self.layer.borderWidth = 1.0
        //How much the edge to be rounded
        self.layer.cornerRadius = 5.0

        // following properties are optional
        //color for border
        self.layer.borderColor = myGreenColor.cgColor
        //color for text
        self.textColor = UIColor.red
        // Mask the bound
        self.layer.masksToBounds = true
        //clip the pixel contents
        self.clipsToBounds = true
    }
}

Output:

enter image description here

Why Extension method?

Create a Swift file and add the following code, which has the Extention method to the "UILabel" class, where this method is user defined but will work for all the label in your application and will help to maintain consistency and clean code, if you change any style in future require only in the extension method.

Aylesbury answered 15/8, 2017 at 13:25 Comment(0)
D
4
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];
Decision answered 21/5, 2014 at 6:44 Comment(0)
S
2

Did you try using the UIButton from the Interface builder (that has rounded corners) and experimenting with the settings to make it look like a label. if all you want is to display static text within.

Sterilization answered 9/3, 2009 at 20:45 Comment(0)
S
2

In Monotouch / Xamarin.iOS I solved the same problem like this:

UILabel exampleLabel = new UILabel(new CGRect(0, 0, 100, 50))
        {
            Text = "Hello Monotouch red label"
        };
        exampleLabel.Layer.MasksToBounds = true;
        exampleLabel.Layer.CornerRadius = 8;
        exampleLabel.Layer.BorderColor = UIColor.Red.CGColor;
        exampleLabel.Layer.BorderWidth = 2;
Suellen answered 14/1, 2016 at 14:23 Comment(0)
Q
2

Works perfect in Swift 2.0

    @IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc


    override func viewDidLoad() {
        super.viewDidLoad()
//Make sure the width and height are same
        self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
        self.theImage.layer.borderWidth = 2.0
        self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
        self.theImage.clipsToBounds = true

    }
Quanta answered 16/4, 2016 at 22:2 Comment(0)
S
0

Depending on what exactly you are doing you could make an image and set it as the background programatically.

Sheela answered 5/11, 2011 at 0:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.