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 ?
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.
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
myLabel.numberOfLines = 1
to your answer, so the minimumScaleFactor works β
Contraceptive Here's the step that work in mine:
- Set width constraint to the label, then click the constraint.
- Select Size Inspector.
- Set the relation to less than or equal, and set max width.
myLabelName.numberOfLines = 0
** This worked for me ( To put Same Text Size, this will put text to a new line on width size reduced) **
We can also use,
myLabelName.adjustsFontSizeToFitWidth = true myLabelName.minimumScaleFactor = 0.5
** This will reduce size of the text on width size reduced. **
you can set lines: 0 , hope its helps.
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.
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
© 2022 - 2024 β McMap. All rights reserved.