user3348253
user3348253

Reputation: 1

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.

Upvotes: 0

Views: 110

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53082

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.

Upvotes: 2

Rafał Sroka
Rafał Sroka

Reputation: 40030

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];

Upvotes: 1

Related Questions