Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 972
Jacob Ahlberg Avatar asked Jun 26 '18 09:06

Jacob Ahlberg


2 Answers

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
    }

}
like image 72
André Slotta Avatar answered Oct 21 '22 22:10

André Slotta


Please update your code as below

 class TagLabel: UILabel {

    override func draw(_ rect: CGRect) {
        let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
        super.drawText(in: rect.insetBy(inset))
    }
}
like image 23
Rakesh Patel Avatar answered Oct 21 '22 23:10

Rakesh Patel