我有一个带有应用约束的自定义 tableview 单元格,但第一次显示表格时,行高未正确调整大小,除非创建新的单元格,有没有办法在不再次调用 reloadData 的情况下执行此操作?
最佳答案
是的。这实际上是一个与 self 调整相关的问题,您需要解决这个问题,直到它被修复。
问题是当一个单元格被实例化时,它的初始宽度是基于 Storyboard的宽度。由于这与 tableView
宽度不同,因此初始布局错误地确定了内容实际需要多少行。
这就是为什么第一次内容的大小不正确,但在您(重新加载数据,或)将单元格滚动到屏幕外然后再屏幕上时正确显示的原因。
您可以通过确保单元格的宽度与 tableView
宽度匹配来解决这个问题。您的初始布局将是正确的,无需重新加载 tableView:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
[cell adjustSizeToMatchWidth:CGRectGetWidth(self.tableView.frame)];
[self configureCell:cell forRowAtIndexPath:indexPath];
return cell;
}
在 TableViewCell.m 中:
- (void)adjustSizeToMatchWidth:(CGFloat)width
{
// Workaround for visible cells not laid out properly since their layout was
// based on a different (initial) width from the tableView.
CGRect rect = self.frame;
rect.size.width = width;
self.frame = rect;
// Workaround for initial cell height less than auto layout required height.
rect = self.contentView.bounds;
rect.size.height = 99999.0;
rect.size.width = 99999.0;
self.contentView.bounds = rect;
}
我还建议查看 smileyborg 的 excellent answer about self-sizing cells ,连同他的 sample code .当我遇到您遇到的相同问题时,这就是让我想到解决方案的原因。
更新:
configureCell:forRowAtIndexPath:
是 Apple 在其示例代码中使用的一种方法。当您有多个 tableViewController
时,通常会对其进行子类化,并在每个 View Controller 中分解特定于 Controller 的 cellForRowAtIndexPath:
代码。父类(super class)处理公共(public)代码(例如使单元格出队)然后调用子类以便它可以配置单元格的 View (这会因 Controller 而异)。如果您不使用子类化,只需将该行替换为特定代码即可设置单元格的(自定义)属性:
cell.textLabel.text = ...;
cell.detailTextLabel.text = ...;
关于ios - UITableViewCell 需要 reloadData() 调整到正确的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060037/