美文网首页
swift PaddingLabel 给label加边距

swift PaddingLabel 给label加边距

作者: 松龄学编程 | 来源:发表于2020-05-16 18:05 被阅读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)
        }
    }
    

    相关文章

      网友评论

          本文标题:swift PaddingLabel 给label加边距

          本文链接:https://www.haomeiwen.com/subject/bxurohtx.html