很多情况下,设置UILabel布局都是自适应的情况,如果你想让文字与边界有一定边距,则需要计算文本的宽高再加上边距值,很不方便。自定义一个UILabel子类可实现想要的效果
import UIKit
class YHBorderLabel: UILabel {
var textInset: UIEdgeInsets = .zero {
didSet {
//每次重新设置初始化大小
invalidateIntrinsicContentSize()
//重绘
setNeedsDisplay()
}
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
return rect.inset(by: textInset.anti)
}
override func drawText(in rect: CGRect) {
//文本的绘区域不变
super.drawText(in: rect.inset(by: textInset))
}
}
extension UIEdgeInsets {
init(padding: CGFloat) {
self.init(top: padding, left: padding, bottom: padding, right: padding)
}
init(horizontal: CGFloat, vertical: CGFloat) {
self.init(top: vertical, left: horizontal, bottom: vertical, right: horizontal)
}
var anti: UIEdgeInsets {
return UIEdgeInsets(top: -top, left: -left, bottom: -bottom, right: -right)
}
}
注意此类最好用于类似于Masonry、snapKit等UILabel自适应的场景。之所以不写分类,主要是上述两个方法就是苹果特意给你子类化重写的,苹果也不建议在分类中重写方法。