9

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?

Community
  • 1
  • 1
Jacob Ahlberg
  • 2,352
  • 6
  • 22
  • 44

4 Answers4

17

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
    }

}
André Slotta
  • 13,774
  • 2
  • 22
  • 34
  • 3
    This is the better answer. If you're finicky enough to be messing with the insets, you're also going to want sizeToFit(). The intrinsicContentSize method above lets that work correctly. – dar512 Mar 25 '20 at 23:16
15

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))
    }
}
sohan vanani
  • 1,537
  • 1
  • 20
  • 37
Rakesh Patel
  • 1,673
  • 10
  • 27
4

this code differs from the accepted answer because the accepted answer uses insetBy(inset) and this answer uses inset(by: inset). When I added this answer in iOS 10.1 and Swift 4.2.1 autocomplete DID NOT give you rect.inset(by: ) and I had to manually type it in. Maybe it does in Swift 5, I'm not sure

For iOS 10.1 and Swift 4.2.1 use rect.inset(by:)

this:

override func draw(_ rect: CGRect) {

    let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)

    super.drawText(in: rect.inset(by: inset))
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256
0

Swift 5 replace method drawText(...) with draw(...)

extension UILabel {

open override func draw(_ rect: CGRect) {
    let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
    super.draw(rect.inset(by: inset))
    
}}
PAULMAX
  • 87
  • 1
  • 11