简体   繁体   中英

UILabel - Multiple Lines

So I have a label in Xcode that loads different text into it depending on different buttons pressed. The text that is loaded into label has varying lengths. The label is big enough to hold all of the different texts that can be loaded but I am having one problem. When there is a lot of text it loads it starting at the top of the label but if the text is only one line long it centers vertically in the label. Is there any way in which I can make sure the text that is loaded into the label will always start on that first line? Thanks in advance.

If you're using auto layout, the height of the label will set itself. Fix the top, leading and trailing edges to the superview, and set numberOfLines = 0 . When you set the text, the height of the textLabel will adjust accordingly.

If you then fix the top of the next subview to the bottom of the label, the spacing between them will be maintained.

There is no vertical alignment property of UILabel that could do it. You can use:

[yourLabel sizeToFit];

to achieve this but it might not be the best solution for you since it will change the frame of the label. Also set your label to be multiline:

yourLabel.numberOfLines = 0;

You can also calculate the CGRect that would fit the text and set it to be the new frame of the UILabel .

CGRect boundingRect = [message boundingRectWithSize:CGSizeMake(your_desired_width, MAXFLOAT)
                                            options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                            context:nil];

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