Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my autolayout label not line wrapping as expected? [duplicate]

First, I create my new label:

UILabel *newLabel=[[UILabel alloc] init];
newLabel.font=[UIFont preferredFontForTextStyle:@"Body"];
newLabel.translatesAutoresizingMaskIntoConstraints=NO;
newLabel.numberOfLines=0;
newLabel.lineBreakMode=NSLineBreakByWordWrapping;
newLabel.text=[NSString stringWithFormat:@"This line is this: %@%@%@",resultString,resultString,resultString];

Then, I create various constraints:

NSArray *labelConstraints=[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]"
                                                                      options:0
                                                                      metrics:nil
                                                                      views:@{@"label": newLabel}];
//Merge the above constraint into a tracking array
labelConstraints=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|"
                                                             options:0
                                                             metrics:nil
                                                               views:@{@"label": newLabel}];
//Again, move the constraint into a tracking array

//Later, we apply all constraints in the tracking array to self.

Unfortunately, the label is not behaving as expected. Assuming I read the above constraint properly, my label should go from one edge of the containing view to the other, horizontally, and not be bound to any given height, vertically. That should, combined with my setting the numberOfLines=0 and lineBreakMode=NSLineBreakByWordWrapping, cause the cell to stretch horizontally to take all necessary lines. Instead, the line is stretching itself out past the edge of the containing view to fit everything onto one line -- and I don't know why!

If it matters, [self] is a subclass of UITableViewCell that I'm trying to program to scale dynamically with content size. If I can just get the contents of the cell to lay themselves out correctly, calculating the actual size of the cell should be relatively easy!

like image 721
RonLugge Avatar asked Jan 12 '23 09:01

RonLugge


1 Answers

You likely need to set the preferredMaxLayoutWidth

See this similar question:

iOS Autolayout: Issue with UILabels in a resizing parent view

like image 91
TomSwift Avatar answered Jan 25 '23 14:01

TomSwift