Set insets on UILabel
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))
}
}
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
}
}
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))
}