Skip to content

Instantly share code, notes, and snippets.

@chrishannah
Last active March 12, 2022 14:01
Show Gist options
  • Save chrishannah/634c476db92bdb040ba4133c82ec6bd6 to your computer and use it in GitHub Desktop.
Save chrishannah/634c476db92bdb040ba4133c82ec6bd6 to your computer and use it in GitHub Desktop.
A simple subclass of UILabel that allows you to add content insets to pad the content.
import UIKit
class InsetLabel: UILabel {
var contentInsets = UIEdgeInsets.zero
override func drawText(in rect: CGRect) {
let insetRect = UIEdgeInsetsInsetRect(rect, contentInsets)
super.drawText(in: insetRect)
}
override var intrinsicContentSize: CGSize {
return addInsets(to: super.intrinsicContentSize)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return addInsets(to: super.sizeThatFits(size))
}
private func addInsets(to size: CGSize) -> CGSize {
let width = size.width + contentInsets.left + contentInsets.right
let height = size.height + contentInsets.top + contentInsets.bottom
return CGSize(width: width, height: height)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment