[ios] How do I create a round cornered UILabel on the iPhone?

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?

This question is related to ios objective-c cocoa-touch uilabel rounded-corners

The answer is


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.


  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


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

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;

xCode 7.3.1 iOS 9.3.2

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;

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.


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://stackoverflow.com/a/33015915/784318
        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://stackoverflow.com/a/15184257/784318
        frame = CGRectInset(self.frame, -borderWidth, -borderWidth)
    }
}


extension UIColor {
    // Credits to https://stackoverflow.com/a/29044899/784318
    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())

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.


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.


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


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>


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://stackoverflow.com/a/33015915/784318
        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://stackoverflow.com/a/15184257/784318
        frame = CGRectInset(self.frame, -borderWidth, -borderWidth)
    }
}


extension UIColor {
    // Credits to https://stackoverflow.com/a/29044899/784318
    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())

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.


    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];

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

    }

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


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>


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;

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.


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


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.


For Swift IOS8 onwards based on OScarsWyck answer:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0

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.


xCode 7.3.1 iOS 9.3.2

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;

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.


  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


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;

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

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;

For Swift IOS8 onwards based on OScarsWyck answer:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0

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

    }

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


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to uilabel

How to make a UILabel clickable? Figure out size of UILabel based on String in Swift How to underline a UILabel in swift? Adding space/padding to a UILabel How to set textColor of UILabel in Swift Adjust UILabel height to text Setting UILabel text to bold How do I make an attributed string using Swift? How do I change the font size of a UILabel in Swift? how do I change text in a label with swift?

Examples related to rounded-corners

ImageView rounded corners How to programmatically round corners and set random background colors Rounded Button in Android Android - drawable with rounded corners at the top only CSS rounded corners in IE8 How to make the corners of a button round? How to make CSS3 rounded corners hide overflow in Chrome/Opera How to round the corners of a button Rounded table corners CSS only UIView with rounded corners and drop shadow?