Resize label to fit text amount - Swift
Asked Answered
P

7

33

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 ?

Physostomous answered 23/7, 2015 at 15:48 Comment(0)
R
58

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.

Ranger answered 23/7, 2015 at 16:15 Comment(2)
how would I go about spacing the content of the label so that it automatically changes rows instead of just outputting a long string of text onto one line? – Involuted
This workes well together with "myLabel.numberOfLines = 0" – Gathers
S
12

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
Splint answered 12/4, 2020 at 10:43 Comment(2)
you should add myLabel.numberOfLines = 1 to your answer, so the minimumScaleFactor works – Contraceptive
@JoãoSerra Eu vou adicionar πŸ‘ – Splint
N
7

Here's the step that work in mine:

  1. Set width constraint to the label, then click the constraint.
  2. Select Size Inspector.
  3. Set the relation to less than or equal, and set max width.

enter image description here

Noellanoelle answered 13/1, 2020 at 10:46 Comment(0)
D
2

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

Dambro answered 11/6, 2021 at 10:49 Comment(0)
D
1

you can set lines: 0 , hope its helps.

Dilettante answered 22/1, 2020 at 1:43 Comment(1)
Please consider adding a short explanation on hao that helps the OP and where can he do the change that you mentioned here – Lytle
H
1

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.

Hospitalet answered 8/11, 2021 at 16:44 Comment(0)
S
-1

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
Seraphic answered 14/12, 2021 at 15:35 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.