Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add padding to the intrinsic content size of UILabel?

Tags:

I'm using autolayout on iOS7 and I have a problem like this:

I'm putting a UILabel onto a UIView and I'm arranging my autolayout constraints so that the label's centerX = parent view's centerX. I'm not giving any width constraint to the label. When I set the label's text on runtime, the label is drawn just wide enough for the text to fit, there are no margins/paddings on the left and right sides. What I want is to have some padding on the left and right sides, so that the text doesn't begin just where the label begins. The hack to achieve this could be setting the text as @" text " but of course that's not the way to go :)

How can I achieve what I want?

like image 648
aslisabanci Avatar asked Jan 01 '14 23:01

aslisabanci


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.

What is content size and intrinsic content size in IOS?

Intrinsic content size is information that a view has about how big it should be based on what it displays. For example, a label's intrinsic content size is based on how much text it is displaying. In your case, the image view's intrinsic content size is the size of the image that you selected.


1 Answers

You can extend UILabel and override the intrinsicContentSize by yourself. Please make sure you have set the textAlignment = NSTextAlignmentCenter as well.

-(CGSize)intrinsicContentSize{     CGSize contentSize = [super intrinsicContentSize];     return CGSizeMake(contentSize.width + 50, contentSize.height); } 

Swift 5.0

open override var intrinsicContentSize: CGSize {     let size = super.intrinsicContentSize     return CGSize(width: size.width + 16, height: size.height) } 

This probably only works when you only have just one line of text to display.

like image 173
Vincent Avatar answered Oct 01 '22 05:10

Vincent