Why doesn't my auto detect label wrap the line as expected?

First I create my new shortcut:

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 shortcut does not behave as expected. Assuming that I read the restriction above correctly, my label should go from one edge of the containing view to the other, horizontally and not snap to any given vertical height. This should, combined with my setting numberOfLines = 0 and lineBreakMode = NSLineBreakByWordWrapping, cause the cell to stretch horizontally to take all the necessary lines. Instead, the line stretches over the edge of the containing view to fit all onto one line — and I don't know why!

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

+4
source share
2 answers

You probably need to set preferredMaxLayoutWidth

See this similar question:

iOS Autolayout: problem with UILabels in parent size view

+5
source

Unfortunately, setting the zero of UILabel numberOfLines to zero does not reproduce very well with automatic layout out of the box. You also need to set the preferredMaxLayoutWidth property.

+4
source

Source: https://habr.com/ru/post/1502507/


All Articles