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

时间:2013-09-16 22:12:10

标签: ios objective-c 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];

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

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.

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

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

2 个答案:

答案 0 :(得分:5)

您可能需要设置preferredMaxLayoutWidth

看到这个类似的问题:

iOS Autolayout: Issue with UILabels in a resizing parent view

答案 1 :(得分:4)

不幸的是,将UILabel的{​​{1}}设置为零并不能很好地与自动布局“开箱即用”。您还需要设置标签的preferredMaxLayoutWidth属性。