Reputation: 1836
I am working on a music player and have labels set up for the song, album, and artist. Now, just for the sake of UI, I would like the song label to always use space for 3 lines, even if the text is 1 line. I have set the number of lines to 3 in the attributes inspector, but it only shows 3 lines if the song title is actually that long!
My first idea of a workaround is to lock the height of the label to 3X the text size(and then some for spacing). Is there maybe a better solution? Or a different object I could use?
Upvotes: 2
Views: 2244
Reputation: 1935
You can try this approach:
Take a UILabel and put it in a UIStackView.
Set the UILabel.amountOfLines = 3
Add another UIView to the UIStackView beneath the label.
Configure auto layout to have the UILabel intrinsic content be with with higher priority than the UIView.
Set the UIStackView height to be constrained exactly to 3 lines height.
The result should be that whatever amount of lines the text is, the Stack view will be in the expected height. But the intrinsic nature will have the text push the label as long as it has text to fill in the 3 lines it has.
As opposed to the accepted answer, you don’t need to care about what the text is, so this is more likely to help other readers who need something of this sort.
Upvotes: 0
Reputation: 580
I needed to accomplish something similar - I needed the UILabel to always be two lines tall, regardless of the text.
After some experimentation, I found that naively adding a new line to the end of the text only gives the desired behavior if the text is one line tall. If the text is already two lines tall due to its content then it results in ellipses at the end of the second line.
I used the code from another question to determine how many lines my text actually renders, and if it is less than desired I append a line feed \n
to the end of the string.
How to find actual number of lines of UILabel?
Just add as many lines feeds to the end as your UILabel as you need to reach your desired number of lines. (note that the code I used from the above question would return 1 line more than the text actually spans, so my logic is something like if desiredLines >= myLabel.numberOfVisibleLines { /*Appened \n to string*/}
)
Upvotes: 0
Reputation: 19469
To force a UILabel to take up three lines as in a music player, you'll just need to add line breaks at the appropriate places with \n
and set the label's lines to 3.
Adding line breaks:
var title = "Title"
var album = "Album"
var artist = "Artist"
label.text = "\(title)\n" +
"\(album)\n" +
"\(artist)\n"
Setting label to 3 lines:
label.numberOfLines = 3 // or set this to 4 or higher if the title of the song might exceed one line
Upvotes: 1