Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel Text Not Wrapping

I am working on a Swift project with Storyboards where I want text to wrap in a label. In the old Objective-C version where I did not use a Storyboard I used the following settings and things worked perfectly.

Objective-C without Storyboard Settings

Here are the settings for Swift

Swift with Storyboard Settings

I have been reading about the potential auto layout issues with preferred width settings. I currently have them set to auto layout and the label itself is set to a width of 560. I've added a constraint to keep the label 20 pixels from the trailing superview and while I thought this would work I still cannot get the text to wrap. The dimension settings are below.

Label Dimension and Constraints

Can someone explain how to get the text to wrap?

like image 982
jonthornham Avatar asked May 25 '15 22:05

jonthornham


3 Answers

First, the good news: You have set the label to 2 lines and Word Wrap. So it can wrap. Excellent.

Now you must make sure the label is tall enough. Either give it no height constraint, or give it a big enough height constraint that it can accommodate two lines.

Finally, you must limit its width. This is what causes the text to wrap. If you don't limit the label's width, it will just keep growing rightward, potentially continuing off the screen. The limit on the label's width stops this rightward growth and causes the text to wrap (and the label to grow downward instead).

You can limit width in several ways. You can have an actual width constraints. Or you can have a leading constraint and a trailing constraint, to something relatively immovable, such as the superview. And there is a third way: on the Size inspector (which you do also show, at the bottom right of your question), set the Preferred Width (it is shown at the top of the Size inspector): this is the width at which, all other things being equal, the label will stop growing to the right and wrap and grow down instead.

like image 72
matt Avatar answered Oct 18 '22 03:10

matt


Declare your UILabel programmatically and give

yourUILabel.contentMode = .scaleToFill
yourUILabel.numberOfLines = 0
yourUILabel.leadingMargin(pixel: 10)
yourUILabel.trailingMargin(pixel: 10)

This worked for me.

like image 16
Vignesh raja Avatar answered Oct 18 '22 03:10

Vignesh raja


Your text will wrap if you have provided lines number more than 1. However you may not be able to see it wrap if the label height is not enough to show the content. I suggest you to remove the height constraint or increase its value.

like image 3
Aman Jain Avatar answered Oct 18 '22 03:10

Aman Jain