How to make UILabel in Swift a circle

Viewed 23368

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?

7 Answers

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

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

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

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
       
    }
Related