AppleTattooGuy
AppleTattooGuy

Reputation: 1175

How to make UILabel in Swift a circle

I am trying to make a UILabel in Swift a perfect circle. I am currently using the following:

pResult.layer.masksToBounds = true
pResult.layer.cornerRadius = 125

The problem with this is that it works fine on 6s plus but any other size it does not become a circle. What is the best way to do this?

Upvotes: 14

Views: 25971

Answers (7)

Faisal Naseer
Faisal Naseer

Reputation: 4248

Create UILabel extension

extension UILabel {
    func addBadge(badgeCount: String) {
       self.text = badgeCount
        self.textColor = UIColor.white
        self.textAlignment = .center
        self.font = UIFont.systemFont(ofSize: 14.0)
       self.layer.cornerRadius = 0.5 * self.bounds.size.width
        self.layer.backgroundColor = UIColor.orange.cgColor
       
    }

Upvotes: 0

Mohamed ALOUANE
Mohamed ALOUANE

Reputation: 5407

Based on the previous answer, but this one in Swift 4.2 :

    label.layer.cornerRadius =  label.frame.width/2
    label.layer.masksToBounds = true

Upvotes: 3

Muzahid
Muzahid

Reputation: 5186

If you you want to make perfect circle then first make sure your label width and height are same.

pResult.layer.cornerRadius = CGRectGetWidth(pResult.frame)/2
pResult.layer.masksToBounds = true

Reference

Upvotes: 11

pansora abhay
pansora abhay

Reputation: 912

If you are using swift 3 then please try this:

lblRoundDot.layer.cornerRadius = lblRoundDot.frame.width/2
lblRoundDot.layer.masksToBounds = true

Upvotes: 5

Ahha Vu
Ahha Vu

Reputation: 1

Depend on the answer of @FruitAddict, i would like to improve it more perfect. You should use .height property instead .width cause in case the length of label be longer (the text increase) this code won't working. And the code will be like this:

pResult.layer.cornerRadius = pResult.frame.height / 2

Upvotes: 0

Hiren Dholariya
Hiren Dholariya

Reputation: 19

//You can provide UserdefiendRunTimeConstraints on the Label using Storyboard or XIB  Select label and give 

(Ex. Your Label Width=100 & Height=100)

 KeyPath =layer.cornerRadius
 Type = Number
 Value = 50

 KeyPath = layer.masksToBounds
 Type = Boolean
 Value = True

 KeyPath = layer.borderWidth
 Type = Number
 Value = 2

Upvotes: 0

FruitAddict
FruitAddict

Reputation: 2032

Circled corners or a full circle? Anyway, assuming that you want the second option, you should constraint the aspect ratio (width:height) to 1:1 on the storyboard so the label is always a square. Then, in the code, you can just do something like

pResult.layer.cornerRadius = pResult.frame.width/2

to always make it a perfect circle, no matter what screen size it will be on.

Upvotes: 24

Related Questions