Yaniv Assaf
Yaniv Assaf

Reputation: 339

Resize label to fit text amount - Swift

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

Answers (7)

Tiago Mendes
Tiago Mendes

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

Ben
Ben

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

iGhost
iGhost

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

Raja Uzair Abdullah
Raja Uzair Abdullah

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

We can also use,

myLabelName.adjustsFontSizeToFitWidth = true myLabelName.minimumScaleFactor = 0.5

** This will reduce size of the text on width size reduced. **

Upvotes: 2

Đỗ Nhật Kha
Đỗ Nhật Kha

Reputation: 71

you can set lines: 0 , hope its helps.

Upvotes: 1

Firda Sahidi
Firda Sahidi

Reputation: 1281

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

Upvotes: 7

mbottone
mbottone

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

Related Questions