Skip to content

Instantly share code, notes, and snippets.

@RayPS
Last active July 27, 2017 08:10
Show Gist options
  • Save RayPS/3725b0bbaa1de6c0dbbc66d3bb58d1a2 to your computer and use it in GitHub Desktop.
Save RayPS/3725b0bbaa1de6c0dbbc66d3bb58d1a2 to your computer and use it in GitHub Desktop.
Padding Label (Subclassing UILabel)
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
// ---------- Usage ----------
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment