Reputation: 339
Hey :) I have a label and I need to make the width of that label smaller or larger accourding to the text amount, and I found only how to adjust the text to fit the size but the how to adjust the size to fit the text, any ideas ?
Upvotes: 33
Views: 71613
Reputation: 5176
sizeToFit() doesn't always work so you should use this:
myLabel.adjustsFontSizeToFitWidth = true
myLabel.minimumScaleFactor = 0.5
myLabel.numberOfLines = 1
Or if you don't have limit lines you can do this:
myLabel.numberOfLines = 0
Upvotes: 12
Reputation: 3804
I had a somewhat different case unrelated to sizeToFit()
. My label had adjustFontSizeToFitWidth = true
and it was oddly adjusting the font size when it did not need to and leaving the label with extra padding at the end.
Simple fix:
myLabel.adjustsFontSizeToFitWidth = false
Upvotes: -1
Reputation: 1054
Many of the above responses work well, but you have to consider the UILabel
's constraints.
For example, if you ensure that the UILabel
will have leadingAnchor and trailingAnchor Constraints with its superview, you can use the .numberOfLines = 0
property, and the height content size will be set automatically.
Upvotes: 1
Reputation: 21
myLabelName.numberOfLines = 0
** This worked for me ( To put Same Text Size, this will put text to a new line on width size reduced) **
myLabelName.adjustsFontSizeToFitWidth = true myLabelName.minimumScaleFactor = 0.5
** This will reduce size of the text on width size reduced. **
Upvotes: 2
Reputation: 1281
Here's the step that work in mine:
Upvotes: 7
Reputation: 1235
You'll want to do this:
myLabel.sizeToFit()
As seen here: https://developer.apple.com/documentation/uikit/uiview/1622630-sizetofit
This will update the label's frame to fit the content. You can then place it or make any edits after this that you want.
Upvotes: 58