简体   繁体   English

如何在 Swift 中使 UILabel 成为一个圆圈

[英]How to make UILabel in Swift a circle

I am trying to make a UILabel in Swift a perfect circle.我试图使 Swift 中的 UILabel 成为一个完美的圆圈。 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.问题在于它在 6s plus 上工作正常,但任何其他尺寸都不会变成圆形。 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.无论如何,假设您想要第二个选项,您应该将故事板上的纵横比(宽度:高度)限制为 1:1,以便标签始终为正方形。 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

Reference 参考

If you are using swift 3 then please try this:如果您使用的是 swift 3,请尝试以下操作:

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

Based on the previous answer, but this one in Swift 4.2 :基于上一个答案,但这个答案在 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) (例如,您的标签宽度 = 100 和高度 = 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.取决于@FruitAddict 的回答,我想把它改进得更完美。 You should use .height property instead .width cause in case the length of label be longer (the text increase) this code won't working.您应该使用 .height 属性而不是 .width 原因,以防标签的长度更长(文本增加)此代码将不起作用。 And the code will be like this:代码将是这样的:

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

Create UILabel extension创建 UILabel 扩展

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
       
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM