swift PaddingLabel 给label加边距

2020-05-16  本文已影响0人  松龄学编程
class PaddingLabel: UILabel {
    var inset: UIEdgeInsets = .zero
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: inset))
    }
    
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        let newRect = CGRect(
            x: rect.origin.x - inset.left,
            y: rect.origin.y - inset.top,
            width: rect.size.width + inset.left + inset.right,
            height: rect.size.height + inset.top + inset.bottom)
        return newRect
    }
}
class MarginLabel: UILabel {
    var margin = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 10)
    override func drawText(in rect: CGRect) {
        let insets = margin
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        guard !(text?.isEmpty ?? false) else { return super.intrinsicContentSize }
        let textSize = sizeThatFits(CGSize(width: bounds.size.width - (margin.left + margin.right), height: CGFloat.greatestFiniteMagnitude))
        return CGSize(width: textSize.width + margin.left + margin.right, height: textSize.height + margin.top + margin.bottom)
    }
}
上一篇下一篇

猜你喜欢

热点阅读