How to make UILabel in Swift a circle

前端 未结 7 1152
孤街浪徒
孤街浪徒 2021-01-04 20:03

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 =          


        
相关标签:
7条回答
  • 2021-01-04 20:20

    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

    0 讨论(0)
  • 2021-01-04 20:23

    If you are using swift 3 then please try this:

    lblRoundDot.layer.cornerRadius = lblRoundDot.frame.width/2
    lblRoundDot.layer.masksToBounds = true
    
    0 讨论(0)
  • 2021-01-04 20:34

    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.

    0 讨论(0)
  • 2021-01-04 20:35

    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
    
    0 讨论(0)
  • 2021-01-04 20:41

    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
           
        }
    
    0 讨论(0)
  • 2021-01-04 20:43
    //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
    
    0 讨论(0)
提交回复
热议问题