有时候我们希望可以设置UILabel的内边距,为了解决这个问题,设计MarginLabel如下,继承自UILabel:
class MarginLabel: UILabel {
var contentInset: UIEdgeInsets = .zero
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect: CGRect = super.textRect(forBounds: UIEdgeInsetsInsetRect(bounds, contentInset), limitedToNumberOfLines: numberOfLines)
//根据edgeInsets,修改绘制文字的bounds
rect.origin.x -= contentInset.left;
rect.origin.y -= contentInset.top;
rect.size.width += contentInset.left + contentInset.right;
rect.size.height += contentInset.top + contentInset.bottom;
return rect
}
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, contentInset))
}
}
实例化一个MarginLabel:
private lazy var marginLabel: MarginLabel = {
MarginLabel().chain
.text("测试UILabel内边距测试UILabel内边距测试UILabel内边距测试UILabel内边距测试UILabel内边距测试UILabel内边距")
.backgroundColor(UIColor.gray)
.textColor(UIColor.white)
.numberOfLines(0)
.build
}()
不设置内边距的时候:
AF6DA567-20B3-47FE-BE0C-406B144BDBD5.png
设置内边距:
marginLabel.contentInset = UIEdgeInsetsMake(10, 10, 10, 10)
效果:
CD59CDD8-EA90-4049-9210-B9534A9FDB4C.png
网友评论