Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 769
Yaniv Assaf Avatar asked Jul 23 '15 15:07

Yaniv Assaf


People also ask

How do I resize a label in Xcode?

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.

What is UI label in Swift?

A view that displays one or more lines of informational text.


3 Answers

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.

like image 192
mbottone Avatar answered Oct 13 '22 09:10

mbottone


sizeToFit() doesn't always work so you should use this:

myLabel.adjustsFontSizeToFitWidth = true
myLabel.minimumScaleFactor = 0.5

Or if you don't have limit lines you can do this:

myLabel.numberOfLines = 0
like image 31
Tiago Mendes Avatar answered Oct 13 '22 09:10

Tiago Mendes


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

like image 24
Firda Sahidi Avatar answered Oct 13 '22 07:10

Firda Sahidi