Created
May 11, 2023 06:34
-
-
Save djryanash/d4dfe038675188d3b8c4edd5a287421f to your computer and use it in GitHub Desktop.
Swift UILabel subclass to add padding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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