示例项目: http://cl.ly/2j0A1J203f3h
我正在尝试使用自动布局来动态确定每个单元格的高度,以便某些单元格可以容纳比其他单元格更多的内容。为此,我使用 this Stackoverflow answer和 accompanying GitHub example .
我有一个名为 CSPostCell
的 UITableViewCell
子类,我在 Storyboard 中创建了它并放入了一个最多 5 行文本的 UILabel
在标签中。
仅出于示例目的,我在表格中只有两个单元格,因此在 cellForRowAtIndexPath:
中设置了两个不同的标签文本(一个较长):
- (CSPostCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell" forIndexPath:indexPath];
cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
[cell setNeedsUpdateConstraints];
return cell;
}
然后我返回每个单元格的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell"];
cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
cell.postTitle.preferredMaxLayoutWidth = tableView.bounds.size.width - 40;
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
}
这或多或少是 GitHub repo example 的精确副本.
但是,当我在模拟器中运行该应用程序时,它并没有按预期运行。高度是动态的,可以针对较长的文本进行调整,但不足以使文本不会被截断。见下图:
在上述情况下,第二个单元格的标签应该显示另一行来结束文本,但它被截断了。
为什么不显示所有文本?
最佳答案
这个简化的代码对我来说效果很好,只有一点点的 2 分。所有对 updateConstraints 的调用似乎都是不必要的。我不确定您为什么需要软糖因素——也许标签中有一些填充?我用不同长度的字符串和不同的字体大小对其进行了测试,它始终可以正常工作。
- (CSPostCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell" forIndexPath:indexPath];
cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell"];
cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
cell.postTitle.preferredMaxLayoutWidth = tableView.bounds.size.width - 40;
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height + 2;
}
关于ios - 当我使用自动布局选择每个单元格的高度(因此它们是动态的)时,它通常可以工作,但有些单元格有点短。为什么是这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20308402/