繁体   English   中英

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

[英]How to make UILabel in Swift a circle

我试图使 Swift 中的 UILabel 成为一个完美的圆圈。 我目前正在使用以下内容:

pResult.layer.masksToBounds = true
pResult.layer.cornerRadius = 125

问题在于它在 6s plus 上工作正常,但任何其他尺寸都不会变成圆形。 做到这一点的最佳方法是什么?

圆角还是整圆? 无论如何,假设您想要第二个选项,您应该将故事板上的纵横比(宽度:高度)限制为 1:1,以便标签始终为正方形。 然后,在代码中,您可以执行以下操作

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

无论屏幕大小如何,始终使它成为一个完美的圆圈。

如果您想制作完美的圆形,请首先确保您的标签宽度和高度相同。

pResult.layer.cornerRadius = CGRectGetWidth(pResult.frame)/2
pResult.layer.masksToBounds = true

参考

如果您使用的是 swift 3,请尝试以下操作:

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

基于上一个答案,但这个答案在 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 

(例如,您的标签宽度 = 100 和高度 = 100)

 KeyPath =layer.cornerRadius
 Type = Number
 Value = 50

 KeyPath = layer.masksToBounds
 Type = Boolean
 Value = True

 KeyPath = layer.borderWidth
 Type = Number
 Value = 2

取决于@FruitAddict 的回答,我想把它改进得更完美。 您应该使用 .height 属性而不是 .width 原因,以防标签的长度更长(文本增加)此代码将不起作用。 代码将是这样的:

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

创建 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