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 =
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
If you are using swift 3 then please try this:
lblRoundDot.layer.cornerRadius = lblRoundDot.frame.width/2
lblRoundDot.layer.masksToBounds = true
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.
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
}
//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