I am an Android developer learning iOS. How do you add padding (inset) to UILabel in iOS Swift? I have not been successful at finding an easy tutorial on this. Thank you.
Also, how can I add margins to UI elements in Swift? When I try the below, nothing gets updated (upon hitting "add constraint").
If alternatively, you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets. You could additionally provide your new subclassed UILabel with insets variables for TOP, LEFT, BOTTOM and RIGHT.
If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.
A view that displays one or more lines of informational text.
These methods just allow you to add a rect (frame) to your textfield's label. newBounds method create the rect (frame) that will be added to textfield's label. Finally your padding is: let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);
This is the code you need to add in Swift 3:
class InsetLabel: UILabel {
let topInset = CGFloat(0)
let bottomInset = CGFloat(0)
let leftInset = CGFloat(20)
let rightInset = CGFloat(20)
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
Probably the best idea is to subclass UILabel
and override drawTextInRect:
like this:
class InsetLabel: UILabel {
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)))
}
}
SWIFT 4+:
class InsetLabel: UILabel {
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With