Skip to content

Instantly share code, notes, and snippets.

@sourleangchhean168
Last active April 23, 2024 04:27
Show Gist options
  • Save sourleangchhean168/acdc746ba9ab175feb6a5f11f16cd97f to your computer and use it in GitHub Desktop.
Save sourleangchhean168/acdc746ba9ab175feb6a5f11f16cd97f to your computer and use it in GitHub Desktop.
Padded Label in Swift 5
//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))
}
}
@sourleangchhean168
Copy link
Author

The PaddedLabel class is a custom subclass of UILabel 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:

  1. Creating an Instance of PaddedLabel:

    let paddedLabel = PaddedLabel()
    paddedLabel.text = "Hello, Padded Label!"
    paddedLabel.padding = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  2. Adding PaddedLabel to a View:

    view.addSubview(paddedLabel)
    paddedLabel.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        paddedLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
        paddedLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20)
    ])
  3. Customizing PaddedLabel:

    paddedLabel.textColor = .blue
    paddedLabel.font = UIFont.systemFont(ofSize: 16)
  4. Updating Padding Dynamically:

    paddedLabel.padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)

Explanation:

  • The padding property allows you to set the padding around the label's text.
  • The intrinsicContentSize override calculates the size of the label including the padding.
  • The drawText(in:) override adjusts the text drawing rect to include the padding.
  • You can create instances of PaddedLabel, set text, padding, and customize it like a regular UILabel.
  • Add the 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment