我试图使Swift中的UILabel成为一个完美的圆形。我目前正在使用以下方法:
pResult.layer.masksToBounds = true
pResult.layer.cornerRadius = 125
这个问题在6s plus上运行良好,但在其他任何尺寸上都不会变成一个圆形。怎样才是最好的解决方法?
圆角还是整个圆圈?无论如何,假设你想要第二个选项,你应该在Storyboard上将纵横比(宽度:高度)限制为1:1,这样标签始终是一个正方形。然后,在代码中,你可以像这样处理:
pResult.layer.cornerRadius = pResult.frame.width/2
始终保持完美的圆形,无论它出现在何种屏幕大小上。
如果您想制作一个完美的圆形,请确保您的标签宽度和高度相同。
pResult.layer.cornerRadius = CGRectGetWidth(pResult.frame)/2
pResult.layer.masksToBounds = true
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
pResult.layer.cornerRadius = pResult.frame.height / 2
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
}
pResult.layer.masksToBounds = true
解决了问题。 - jamix