Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel text margin [duplicate]

I'm looking to set the left inset/margin of a UILabel and can't find a method to do so. The label has a background set so just changing its origin won't do the trick. It would be ideal to inset the text by 10px or so on the left hand side.

like image 642
Ljdawson Avatar asked Aug 13 '10 12:08

Ljdawson


People also ask

How do you control line spacing in UILabel?

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels." This is a really old answer, and other have already addded the new and better way to handle this..

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.

What is UILabel?

A view that displays one or more lines of informational text.

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


1 Answers

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)]; } 

Swift 3.1:

override func drawText(in rect: CGRect) {     let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)     super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) } 

Swift 4.2.1:

override func drawText(in rect: CGRect) {     let insets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)     super.drawText(in: rect.inset(by: insets)) } 

As you might have gathered, this is an adaptation of tc.'s answer. It has two advantages over that one:

  1. there's no need to trigger it by sending a sizeToFit message
  2. it leaves the label frame alone - handy if your label has a background and you don't want that to shrink
like image 82
Tommy Herbert Avatar answered Oct 26 '22 00:10

Tommy Herbert