In this article we will learn how to add margins/padding to the label using custom UIEdgeInsets.
In the above image we can clearly see "without padding" and "with padding".
"Without padding" is not looking great, so usually developers prefer labels with padding.
Download sample project with example :
In the above image we can clearly see "without padding" and "with padding".
"Without padding" is not looking great, so usually developers prefer labels with padding.
Step 1:
Create new swift file and add the following code:import UIKit
class SSPaddingLabel: UILabel {
var padding : UIEdgeInsets
// Create a new SSPaddingLabel instance programamtically with the desired insets
required init(padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) {
self.padding = padding
super.init(frame: CGRect.zero)
}
// Create a new SSPaddingLabel instance programamtically with default insets
override init(frame: CGRect) {
padding = UIEdgeInsets.zero // set desired insets value according to your needs
super.init(frame: frame)
}
// Create a new SSPaddingLabel instance from Storyboard with default insets
required init?(coder aDecoder: NSCoder) {
padding = UIEdgeInsets.zero // set desired insets value according to your needs
super.init(coder: aDecoder)
}
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
}
// Override `intrinsicContentSize` property for Auto layout code
override var intrinsicContentSize: CGSize {
let superContentSize = super.intrinsicContentSize
let width = superContentSize.width + padding.left + padding.right
let heigth = superContentSize.height + padding.top + padding.bottom
return CGSize(width: width, height: heigth)
}
// Override `sizeThatFits(_:)` method for Springs & Struts code
override func sizeThatFits(_ size: CGSize) -> CGSize {
let superSizeThatFits = super.sizeThatFits(size)
let width = superSizeThatFits.width + padding.left + padding.right
let heigth = superSizeThatFits.height + padding.top + padding.bottom
return CGSize(width: width, height: heigth)
}
}
Step 2:
Create label and set content insets as follow:let label = SSPaddingLabel() label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true label.backgroundColor = UIColor.white label.padding = UIEdgeInsetsMake(8, 15, 8, 15) label.text = "Hello Padding!" label.sizeToFit() label.layer.cornerRadius = label.frame.height/2 label.layer.masksToBounds = true
Download sample project with example :



No comments:
Post a Comment