iOS|iOS UILabel设置内边距

有时候我们希望可以设置UILabel的内边距,为了解决这个问题,设计MarginLabel如下,继承自UILabel:

class MarginLabel: UILabel {var contentInset: UIEdgeInsets = .zerooverride 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 }()

不设置内边距的时候:

iOS|iOS UILabel设置内边距
文章图片
AF6DA567-20B3-47FE-BE0C-406B144BDBD5.png 设置内边距:
marginLabel.contentInset = UIEdgeInsetsMake(10, 10, 10, 10)

【iOS|iOS UILabel设置内边距】效果:

iOS|iOS UILabel设置内边距
文章图片
CD59CDD8-EA90-4049-9210-B9534A9FDB4C.png

    推荐阅读