UILabel 的圆角 swift

Rounded corners of UILabel swift

我正在以编程方式创建 UILabel。但是下面的代码没有给我圆角。我想我错过了一些非常基本的东西。

var textLabel:UILabel? =  UILabel()
textLabel?.text = text
textLabel?.frame = CGRect(x:point.x, y:point.y, width:(textLabel?.intrinsicContentSize.width)!, height:15)
textLabel?.backgroundColor = UIColor.white
textLabel?.font = UIFont(name:"OpenSans", size:8)
textLabel?.sizeToFit()
textLabel?.layer.cornerRadius = 20.0

谁能给我指出正确的方向?

为您的标签设置 masksToBounds

masksToBounds act as a Boolean indicating whether sublayers are clipped to the layer’s bounds.

textLabel?.layer.cornerRadius = 20.0
textLabel?.layer.masksToBounds = true

参考苹果 documents.

试试这个:

yourLabel.layer.cornerRadius = 8.0
yourLabel.layer.masksToBounds = true
yourLabel.layer.borderColor = UIColor.white.cgColor
yourLabel.layer.borderWidth = 1.0

这应该会给你圆角边框

关键是 属性 "maskToBounds",它是一个布尔值,指示子层是否被裁剪到层的边界。

试试这个:-

textLabel?.layer.cornerRadius = textLabel?.frame.size.height/2.0

textLabel?.layer.masksToBounds = true

如果你想设置边框颜色那么:-

  textLabel?.layer.borderColor = .red.cgColor
  textLabel?.layer.borderWidth = 1.0

我认为您应该为 textLabel 设置 maskToBounds。试试这个:

textLabel?.layer.masksToBounds = true

swift 4.2

设置标签角半径并正常工作

labelVerified.layer.cornerRadius = 6
labelVerified.layer.masksToBounds = true