Created
May 16, 2018 09:09
-
-
Save simme/cbf22d2ff84b09edc5f0e6854b7411b5 to your computer and use it in GitHub Desktop.
A `UILabel` subclass that allows content padding.
This file contains hidden or 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
// 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