Last active
April 23, 2024 04:27
-
-
Save sourleangchhean168/acdc746ba9ab175feb6a5f11f16cd97f to your computer and use it in GitHub Desktop.
Padded Label in Swift 5
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
//Created by SOUR LEANGCHHEAN | |
class PaddedLabel: UILabel { | |
// MARK: - Properties | |
var padding: UIEdgeInsets = .zero { | |
didSet { | |
invalidateIntrinsicContentSize() | |
} | |
} | |
// MARK: - Overrides | |
override var intrinsicContentSize: CGSize { | |
var size = super.intrinsicContentSize | |
size.width += padding.left + padding.right | |
size.height += padding.top + padding.bottom | |
return size | |
} | |
// MARK: - Initializers | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
} | |
// MARK: - Drawing | |
override func drawText(in rect: CGRect) { | |
super.drawText(in: rect.inset(by: padding)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
PaddedLabel
class is a custom subclass ofUILabel
in Swift that allows you to add padding around the text displayed within the label. Here's an example of how you can use this class:Example Usage:
Creating an Instance of PaddedLabel:
Adding PaddedLabel to a View:
Customizing PaddedLabel:
Updating Padding Dynamically:
Explanation:
padding
property allows you to set the padding around the label's text.intrinsicContentSize
override calculates the size of the label including the padding.drawText(in:)
override adjusts the text drawing rect to include the padding.PaddedLabel
, set text, padding, and customize it like a regularUILabel
.PaddedLabel
to your view hierarchy and position it using Auto Layout or frame-based layout.By using the
PaddedLabel
class, you can easily create labels with padding around the text, providing a more visually appealing and customizable way to display text in your app.