Skip to content

Instantly share code, notes, and snippets.

@muratyasarr
Last active August 15, 2020 04:45
Show Gist options
  • Save muratyasarr/452618685dc9651b544b3c0dca1573e8 to your computer and use it in GitHub Desktop.
Save muratyasarr/452618685dc9651b544b3c0dca1573e8 to your computer and use it in GitHub Desktop.
class LabelWithPadding: UILabel {
@objc var padding = UIEdgeInsets.zero {
didSet { invalidateIntrinsicContentSize() }
}
@IBInspectable public var bottomInset: CGFloat {
get { return padding.bottom }
set { padding.bottom = newValue }
}
@IBInspectable public var leftInset: CGFloat {
get { return padding.left }
set { padding.left = newValue }
}
@IBInspectable public var rightInset: CGFloat {
get { return padding.right }
set { padding.right = newValue }
}
@IBInspectable public var topInset: CGFloat {
get { return padding.top }
set { padding.top = newValue }
}
init() {
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: padding)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -padding.top,
left: -padding.left,
bottom: -padding.bottom,
right: -padding.right)
return textRect.inset(by: invertedInsets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
override var intrinsicContentSize: CGSize {
var superSize = super.intrinsicContentSize
superSize.height += self.padding.top + self.padding.bottom
superSize.width += self.padding.left + self.padding.right
return superSize
}
override var bounds: CGRect {
didSet {
// ensures this works within stack views if multi-line
preferredMaxLayoutWidth = bounds.width - (leftInset + rightInset)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment