Skip to content

Instantly share code, notes, and snippets.

@djryanash
Created May 11, 2023 06:34
Show Gist options
  • Save djryanash/d4dfe038675188d3b8c4edd5a287421f to your computer and use it in GitHub Desktop.
Save djryanash/d4dfe038675188d3b8c4edd5a287421f to your computer and use it in GitHub Desktop.
Swift UILabel subclass to add padding.
class UILabelPadded: UILabel {
var textEdgeInsets = UIEdgeInsets(
top: 5,
left: 10,
bottom: 5,
right: 10)
open override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: textEdgeInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -textEdgeInsets.top, left: -textEdgeInsets.left, bottom: -textEdgeInsets.bottom, right: -textEdgeInsets.right)
return textRect.inset(by: invertedInsets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textEdgeInsets))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment