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?
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.
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
If you are using swift 3 then please try this:
lblRoundDot.layer.cornerRadius = lblRoundDot.frame.width/2
lblRoundDot.layer.masksToBounds = true
Based on the previous answer, but this one in Swift 4.2 :
label.layer.cornerRadius = label.frame.width/2
label.layer.masksToBounds = true
//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
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.