有時(shí)候我們希望可以設(shè)置UILabel的內(nèi)邊距迅箩,為了解決這個(gè)問題,設(shè)計(jì)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)
//根據(jù)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))
}
}
實(shí)例化一個(gè)MarginLabel:
private lazy var marginLabel: MarginLabel = {
MarginLabel().chain
.text("測(cè)試UILabel內(nèi)邊距測(cè)試UILabel內(nèi)邊距測(cè)試UILabel內(nèi)邊距測(cè)試UILabel內(nèi)邊距測(cè)試UILabel內(nèi)邊距測(cè)試UILabel內(nèi)邊距")
.backgroundColor(UIColor.gray)
.textColor(UIColor.white)
.numberOfLines(0)
.build
}()
不設(shè)置內(nèi)邊距的時(shí)候:
AF6DA567-20B3-47FE-BE0C-406B144BDBD5.png
設(shè)置內(nèi)邊距:
marginLabel.contentInset = UIEdgeInsetsMake(10, 10, 10, 10)
效果:
CD59CDD8-EA90-4049-9210-B9534A9FDB4C.png