I need to create a UILabel
with a background color, and I'd like to add some left/right leading/trailing horizontal padding.
But every solution I've found seems like a nasty hack.
What is the 'standard' way to achieve this from iOS 5 forward?
A screenshot to illustrate my scenario:
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.
You should use a container view and place the label inside of that. Then add constraints for the label, which will be equivalent to a padding. Select the label and click the constraints panel at the bottom right in the Storyboard file.
"label. layer. masksToBounds = true" is an important code, if you apply corner radius to a label and if it dosen't work than adding this will definitely add the corner radius to a particular label.. So this should be the correct answer..
For a full list of available solutions, see this answer: UILabel text margin
Try subclassing UILabel, like @Tommy Herbert suggests in the answer to [this question][1]. Copied and pasted for your convenience:
I solved this by subclassing UILabel and overriding drawTextInRect: like this:
- (void)drawTextInRect:(CGRect)rect { UIEdgeInsets insets = {0, 5, 0, 5}; [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; }
The most important part is that you must override both intrinsicContentSize()
and drawTextInRect()
in order to account for AutoLayout:
var contentInset: UIEdgeInsets = .zero { didSet { setNeedsDisplay() } } override public var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize(width: size.width + contentInset.left + contentInset.right, height: size.height + contentInset.top + contentInset.bottom) } override public func drawText(in rect: CGRect) { super.drawText(in: UIEdgeInsetsInsetRect(rect, contentInset)) }
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