前言:
经常在某 App 上看到文字 Label 带有圆角边框之类的, 如果直接设置 Label 的layer 圆角属性, 会发现圆角太靠近文字了,黏在一起不好看,我以前的做法是, 弄一个 UIView, 上面放个 UILabel, 这个办法其实很辣鸡. 我从没有使用过这种方法.
今天看到了一个不错的方法, 这里记录一下.
效果图
代码
import UIKit
class YXPaddingLabel: UILabel {
var circularFillet = false
let padding = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8)
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
}
override var intrinsicContentSize : CGSize {
let superContentSize = super.intrinsicContentSize
let width = superContentSize.width + padding.left + padding.right
let heigth = superContentSize.height + padding.top + padding.bottom
return CGSize(width: width, height: heigth)
}
override func layoutSubviews() {
super.layoutSubviews()
if circularFillet == true {
let h = self.layer.frame.size.height
self.layer.cornerRadius = h / 2
}
}
}
图片中的示例代码
labelOriginal.layer.borderColor = UIColor.red.cgColor
labelOriginal.layer.borderWidth = 1
labelOriginal.font = UIFont.systemFont(ofSize: 20)
label1.layer.borderColor = UIColor.red.cgColor
label1.layer.borderWidth = 1
label1.font = UIFont.systemFont(ofSize: 20)
label2.layer.cornerRadius = 10
label2.layer.borderColor = UIColor.red.cgColor
label2.layer.borderWidth = 1
label2.font = UIFont.systemFont(ofSize: 20)
label3.layer.borderColor = UIColor.red.cgColor
label3.layer.borderWidth = 1
label3.font = UIFont.systemFont(ofSize: 20)
label3.circularFillet = true
let label4 = YXPaddingLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label4.center = view.center
label4.textAlignment = .center
label4.textColor = UIColor.purple
label4.text = "自定义控件4"
label4.layer.cornerRadius = 25
label4.layer.backgroundColor = UIColor.yellow.cgColor
label4.layer.borderColor = UIColor.red.cgColor
label4.layer.borderWidth = 1
label4.font = UIFont.systemFont(ofSize: 20)
view.addSubview(label4)