Skip to content

Instantly share code, notes, and snippets.

@simme
Created May 16, 2018 09:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simme/cbf22d2ff84b09edc5f0e6854b7411b5 to your computer and use it in GitHub Desktop.
Save simme/cbf22d2ff84b09edc5f0e6854b7411b5 to your computer and use it in GitHub Desktop.
A `UILabel` subclass that allows content padding.
// MIT License applies.
import UIKit
/**
A `UILabel` subclass that provides a way of adding padding to the label.
*/
open class Label: UILabel {
/// The amount of padding for each side in the label.
@objc dynamic open var edgeInsets = UIEdgeInsets.zero {
didSet {
setNeedsLayout()
invalidateIntrinsicContentSize()
}
}
open override var bounds: CGRect {
didSet {
// This fixes an issue where the last line of the label would sometimes be cut off.
if numberOfLines == 0 {
let boundsWidth = bounds.width - edgeInsets.left - edgeInsets.right
if preferredMaxLayoutWidth != boundsWidth {
preferredMaxLayoutWidth = boundsWidth
setNeedsUpdateConstraints()
}
}
}
}
open override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, edgeInsets))
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += edgeInsets.left + edgeInsets.right
size.height += edgeInsets.top + edgeInsets.bottom
// There's a UIKit bug where the content size is sometimes one point to short. This hacks that.
if numberOfLines == 0 { size.height += 1 }
return size
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
var parentSize = super.sizeThatFits(size)
parentSize.width += edgeInsets.left + edgeInsets.right
parentSize.height += edgeInsets.top + edgeInsets.bottom
return parentSize
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment