iosswiftuiedgeinsets

Set insets on UILabel


I'm trying to set some insets in a UILabel. It worked perfectly, but now UIEdgeInsetsInsetRect has been replaced with CGRect.inset(by:) and I can't find out how to solve this.

When I'm trying to use CGRect.inset(by:) with my insets, then I'm getting the message that UIEdgeInsets isn't convertible to CGRect.

My code

class TagLabel: UILabel {
    
    override func draw(_ rect: CGRect) {
        let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
        
        super.drawText(in: CGRect.insetBy(inset))
//        super.drawText(in: UIEdgeInsetsInsetRect(rect, inset)) // Old code
    }

}

Anyone knows how to set the insets to the UILabel?


Solution

  • Imho you also have to update the intrinsicContentSize:

    class InsetLabel: UILabel {
    
        let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
    
        override func drawText(in rect: CGRect) {
            super.drawText(in: rect.inset(by: inset))
        }
    
        override var intrinsicContentSize: CGSize {
            var intrinsicContentSize = super.intrinsicContentSize
            intrinsicContentSize.width += inset.left + inset.right
            intrinsicContentSize.height += inset.top + inset.bottom
            return intrinsicContentSize
        }
    
    }