Dakata Dakata - 1 year ago 139
Swift Question

How can I display larger text in small Label.text?

I am a beginner in swift and I am developing my first application. The problem I am having right now is a large text which should be displayed in a small label.text.

I have tried some of these codes:

Label.text = "The text I want to see here is too big for the size of the label"
Label.numberOfLines = 0

But it seems that it is not working. I would be very glad if someone give me an advice how to do it. I was thinking about scrolling from left to right -> and displaying the whole sentence or even tapping over the label and displaying a small window with the entire text.

Would you please tell me is that possible and provide me with an example which I can use in my code.

Answer Source

label.sizeToFit does not shrink text to fit the label but rather changes the size of the label to fit around the text that you have set for the label.

Without creating a new pop-up window or something like that your best bet is either shrinking the font size or allowing the label to have multiple lines of text.

For shrinking, what I would suggest is using the following:

 label.adjustsFontSizeToFitWidth = true

This will shrink the size of your text to fit the label. This may end up acting weird if your text is really long compared to the width of the label, so be careful.

For multiple lines in the label try something like this:

 label.lineBreakMode = NSLineBreakByWordWrapping;
 label.numberOfLines = 0;


Since it seems that you have no space for extra lines, what I would suggest is embedding the label in a scrollView, so that it could scroll horizontally so you can see all of the text.

This could be accomplished by the following:

var scrollView: UIScrollView = UIScrollView(frame: label.frame) //you can initialize this with the frame of your label
scrollView.contentSize.height = label.frame.height
scrollView.contentSize.width = label.frame.width
scrollView.showsVerticalScrollIndicator = false //no vertical scroll bars
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download