Last active
July 27, 2017 08:10
-
-
Save RayPS/3725b0bbaa1de6c0dbbc66d3bb58d1a2 to your computer and use it in GitHub Desktop.
Padding Label (Subclassing UILabel)
This file contains 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
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