We generally do not add padding to a label. We use another solution:
- You can increase leading and trailing constraints from 0 to whatever you need.
- You can create another
UIView
on which you place your label. The label should have leading and trailing constraints as much as you want your padding. This should automatically resize your view
- Use
UIButton
which already has content insets in Storyboard. Disable its user interaction. (It is an overkill but it is A solution).
If you really really want this though you can create a subclass of UILabel
and add this functionality in just few lines:
@IBDesignable class AppLabel: UILabel {
@IBInspectable var horizontalPadding: CGFloat = 0.0 { didSet { invalidateIntrinsicContentSize() } }
@IBInspectable var verticalPadding: CGFloat = 0.0 { didSet { invalidateIntrinsicContentSize() } }
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += horizontalPadding*2.0
size.height += verticalPadding*2.0
return size
}
}
Now you can even in storyboard set vertical and horizontal padding. But you need to have center text alignment. The key is overriding intrinsicContentSize
which is what defines this automatic sizing. Simply some value is added to it and it works.
I would personally still avoid this but perhaps it is still better than using UIButton
.