Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add left/right horizontal padding to UILabel

Tags:

ios

uilabel

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:

left padding needed

like image 438
ssantos Avatar asked Oct 17 '13 21:10

ssantos


People also ask

How do I add padding to UILabel?

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.

How do I add padding to labels in Xcode?

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.

How do you label corner radius in Swift?

"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..


2 Answers

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)]; } 
like image 83
siege_Perilous Avatar answered Oct 04 '22 15:10

siege_Perilous


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)) } 
like image 33
Mike Avatar answered Oct 04 '22 16:10

Mike