当我使用自动布局选择每个单元格的高度(因此它们是动态的)时,它主要起作用,但有些单元格有点短。 为什么是这样?
示例项目: http : //cl.ly/2j0A1J203f3h
我正在尝试使用自动布局来动态确定每个单元格的高度,以便某些单元格可以容纳更多内容。 为此,我使用此Stackoverflow答案和随附的GitHub示例 。
我有一个名为CSPostCell
的UITableViewCell
子类,我在Storyboard中创建了一个UILabel
,标签中最多包含5行文本。
仅作为示例,我在表中只有两个单元格,因此在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示例中的精确副本。
但是,当我在模拟器中运行应用程序时,它并没有完全正常工作。 高度是动态的,可以根据较长的文本进行调整,但不足以使文本不被切断。 见下图:
在上面的情况下,第二个单元格的标签应显示另一行来完成文本,但它会被切断。
为什么没有显示所有文字?
这个简化的代码对我来说效果很好,只有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; }