如何使用 Swift 实现 UILabel 的圆边

我已经查看了 Xcode 6.3中的 label 属性,但是我还没有找到如何像圆整文本字段的边一样圆整边缘的方法。

88253 次浏览

假设您已经将 backgroundColor添加到您的标签中,否则将无法判断它是否有边缘,您可以使用 QuartzCore 来圆滑标签的边缘。

import QuartzCore


yourLabel.layer.backgroundColor  = UIColor.redColor().CGColor
yourLabel.layer.cornerRadius = 5
yourLabel.layer.masksToBounds = true

绕过任何 CALayer的一个方法是修改 layer.cornerRadius。默认情况下,这只会影响背景颜色和你应用的任何图层边框。还可以启用 clipsToBounds来剪辑像素内容。

当一个视图(如 UILabel)自我绘制时,它将自我绘制到图层的像素内容。你可以抓取 view.layer访问层。

因此,您可以设置该图层的角半径来影响视图的背景颜色。您还可以启用 clipsToBounds来裁剪视图中的任何内容。如果视图本身不是太靠近边缘,那么应该可以达到您想要的效果。标签应该是正确的。

使用标签层的角半径来做到这一点,

mylabel.layer.cornerRadius = yourvalue

如果你不想显示阴影然后添加,

mylabel.layer.masksToBounds = true

我觉得挺好的。

诀窍是将 maskToBounds设置为 true。然后您对 cornerRadius的修改将是可见的。

label.layer.masksToBounds = true
label.layer.cornerRadius = 5

在2017年8月进行测试,在 Xcode 使用 Swift 3工作良好8.1.2

“角半径”是设置圆角边缘的关键属性,如果您在应用程序中对所有标签使用相同的样式,我建议使用扩展方法。

密码:

  // extension Class
extension UILabel {


// extension user defined Method
func setRoundEdge() {
let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
//Width of border
self.layer.borderWidth = 1.0
//How much the edge to be rounded
self.layer.cornerRadius = 5.0


// following properties are optional
//color for border
self.layer.borderColor = myGreenColor.cgColor
//color for text
self.textColor = UIColor.red
// Mask the bound
self.layer.masksToBounds = true
//clip the pixel contents
self.clipsToBounds = true
}
}

产出:

enter image description here

为什么使用扩展方法?

创建一个 Swift 文件并添加以下代码,该代码在“ UILabel”类中使用了 Extended 方法,这个方法是用户定义的,但是可以用于应用程序中的所有标签,并且有助于保持一致性和清晰的代码,如果你将来改变任何样式只需要在扩展方法中使用。

你可以给 cornerRadius和边框像这样。

为了斯威夫特543

MyLable.layer.masksToBounds = true
MyLable.layer.cornerRadius = 6
MyLable.layer.borderWidth = 2
MyLable.layer.borderColor = UIColor.black.cgColor

目标 C

[MyLable.layer setMasksToBounds:TRUE];
[MyLable.layer setCornerRadius:6];
[MyLable.layer setBorderWidth:2];
[MyLable.layer setBorderColor:[UIColor blackColor].CGColor];

您可以使用 IBChectable 为 UIView 创建一个扩展

extension UIView {


@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}


@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}


@IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
}

enter image description here

选择你的 UILabel

在检查器中,添加 layer.masksToBoundslayer.cornerRadius

Easy way to achieve rounded corners for label

在类中处理的代码更少

斯威夫特:

//round shape corner radius set
self.lblName.layer.masksToBounds = true
self.lblName.layer.cornerRadius = self.lblName.bounds.width / 2


//custom shape corner radius set
self.lblName.layer.masksToBounds = true
self.lblName.layer.cornerRadius = 12