简体   繁体   中英

swift how to make ui label always 4 lines

This is my code

aboutMessageLabel.lineBreakMode = .ByWordWrapping
//                .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
            aboutMessageLabel.numberOfLines = 4
            aboutMessageLabel.text = "bla bla"

where aboutmessageLabel is an instance of UILabel.

If my content is more than 4 lines, it shows just the first 4 lines and that is what I want.

However, if the content is less than 4 lines, it the height doesn't keep as the hieght for 4 lines, it becomes the hieght of the content.

is there anyway where i can always make the label 4 lines even if the content is less than 4 lines?

Set the size of the label in the MainStoryboard (like in the 2nd image), then click on your label, then in the Attributes Inspector set the number or Lines to 4 like this:

在此处输入图片说明

Your label will have 4 lines, no matter who much text there is (which can be a bad thing as well if you have too much text like in the example):

在此处输入图片说明

Furthermore, did you should add constraints to the label. This will keep it the same size always. I'm assuming you want to create something like a meta description of a product, song, whatever. So if you keep the same size and have the 4 lines set, you'll be fine. It'll adjust based on the number of words while keeping the size. Edit the color of the label background to see the if it works/stays the same size when testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM