4
votes

I am very new to Swift and I don't know how to make my UILabel show all text.

Here is how my label looks like in my storyboard:enter image description here

As you see, part of the text is omitted. I can show all the text by dragging the UILabel to resize. However, during the runtime, if the text is set dynamically, how can I resize the label so that it can show more all of the text?

I tried UILabel.sizeToFit() but that doesn't seem to change anything.

5

5 Answers

9
votes

you can do this by setting numberOfLines to 0

Example

 myLabel.text = "whatever"
 myLabel.numberOfLines = 0
 myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

And you have so set frame according to it

Refer : to this link

4
votes

YourUILabel.sizeToFit() is right but that is not all of it..

You need to set the number of lines and the kind of line break before calling .sizeToFit()..

YourUILabel.numberOfLines equal to 0 for unlimited number of lines...

YourUILabel.lineBreakMode equal to NSLineBreakMode dot(.) ByWordWrapping for example..

2
votes

If you are not resizing the UILabel frame using autolayout you can change the Autoshrink option by selecting your label from the storyboard and adjust this option on the inspector pane.

enter image description here.

1
votes

Why do it the old way.. Let's use autolayout. If you haven't used it yet. Lets begin - Steps :

  1. Create a UIlabel and set it's width to any amount you want it on screen.

  2. Select the label go to Editor menu -> Pin and one by one pin Leading Trailing and Top space to Superview (not the bottom one).

  3. Since you have fixed width and you have dynamic height so also pin Width.

  4. Go to Attribute inspector tab and set lines to 0 (means unlimited).

  5. Go To size inspector and set Content Hugging priority(250/251) to low and Content Resistance priority to high (say - 750).

And you are done.!!(not a single line of code)

0
votes

You first have to calculate the Height of label according to the length of the Text you want to set and then accordingly increase the number of lines as

yourLabel.numberOfLines = "Your calculation number"

and then Set the Frame of the Label according to the Height calculated and

if you cannot calculate the height of the Label then i would say use the TextView it will automatically add a scroll to the text and you can view all the text.