为什么我的autolayout标签没有按预期换行?

Ron*_*gge 4 objective-c ios autolayout

首先,我创建了我的新标签:

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];
Run Code Online (Sandbox Code Playgroud)

然后,我创建了各种约束:

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.
Run Code Online (Sandbox Code Playgroud)

不幸的是,标签表现不如预期.假设我正确地阅读了上述约束,我的标签应该从包含视图的一个边缘水平地移动到另一个边缘,而不是垂直地绑定到任何给定的高度.这应该与我设置的numberOfLines = 0和lineBreakMode = NSLineBreakByWordWrapping相结合,使单元格水平拉伸以获取所有必要的线条.相反,这条线将自己拉伸到包含视图的边缘以使所有东西都适合一条线 - 我不知道为什么!

如果重要,[self]是UITableViewCell的子类,我正在尝试编程以随内容大小动态扩展.如果我可以让单元格的内容正确显示出来,那么计算单元格的实际大小应该相对容易!

Tom*_*ift 5

你可能需要设置 preferredMaxLayoutWidth

看到这个类似的问题:

iOS Autolayout:调整大小父视图中的UILabel问题