UITableViewCell中的多行UILabel在iOS8中使用autoLayout给出了错误的高度

时间:2015-09-01 09:10:01

标签: ios uitableview uilabel

我一直在阅读我在这里找到的具有动态高度和多线标签的细胞的其他人解决方案,但它们似乎都没有100%工作。

Cell有以下垂直约束:Vertical cell constraints

tableView配置为:

self.tableView.estimatedRowHeight = 100;
self.tableView.rowHeight = UITableViewAutomaticDimension;

在方法tableview中:cellForRowAtIndexPath:我设置多行标签的preferredMaxLayoutWidth:

JBLabelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JBLabelTableViewCell" forIndexPath:indexPath];
NSString *labelText = [self.items objectAtIndex:indexPath.item];
[cell.bodyLabel setText:labelText];
CGRect cellFrame = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), 99999);
[cell setBounds:cellFrame];
cell.contentView.bounds = cell.bounds;
[cell layoutIfNeeded];
[cell.bodyLabel setPreferredMaxLayoutWidth:CGRectGetWidth(cell.bodyLabel.frame)];
return cell;

使用以下两个字符串设置dataSource:

_items = @[@"On this screen you can see the groups of people that you have set yourself up to chat with.\n\nCommunities are groups of people that are created for you on the basis of your interests, and how you feel about your condition, or the conditions of those you care about.\n\nThey are not only there to provide you with help or someone to talk to but can also benefit from the help and support that you can give.",
               @"On this screen you can see a list of the conversations that you are involved in.\n\nWithin conversations you can ask questions to like-minded people or just have someone to chat to. These are places where you can help someone or get someone to help you."];

在iPhone 6模拟器中运行项目,第一个字符串的最后一行被截止:iPhone screenshot

所有对象之间的约束看起来正确,但多线标签的计算高度不适合第一个字符串。

是否有人遇到此问题并有解决方案?

感谢。

1 个答案:

答案 0 :(得分:2)

你的代码可能是正确的。我只是添加了这两行(没必要说。你已经添加过截图了!)

cell. bodyLabel.numberOfLines = 0;
cell. bodyLabel.lineBreakMode = NSLineBreakByWordWrapping;

您的问题似乎在于您的用户界面。这是我用于UITableViewCell的用户界面,它工作得很好 enter image description here

<强>更新<!/强>

只需将此添加到viewDidLoad [self.view layoutIfNeeded]; [self.view setNeedsLayout]; 在viewDidLoad中正在使用用户界面的框架,您需要更新约束和视图以使用设备屏幕框架layoutIfNeeded和setNeedsLayout的顺序非常重要。你需要先调用layoutIfNeeded。