我有一个带有自定义UITableViewCell
的UITableView
,它是使用自动布局在情节提要中定义的。该单元具有多个多行UILabels
。
UITableView
似乎正确地计算了单元格的高度,但对于前几个单元格,标签之间的高度没有正确划分。滚动一下之后,一切都会正常工作(即使是最初不正确的单元格)。
- (void)viewDidLoad {
[super viewDidLoad]
// ...
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TestCell"];
// ...
// Set label.text for variable length string.
return cell;
}
有没有什么我可能遗漏的,导致自动布局在最初几次不能完成它的工作?
我已经创建了一个sample project来演示这种行为。
发布于 2014-09-22 17:58:36
我不知道这是否有明确的文档,但是在返回单元格之前添加[cell layoutIfNeeded]
可以解决您的问题。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TestCell"];
NSUInteger n1 = firstLabelWordCount[indexPath.row];
NSUInteger n2 = secondLabelWordCount[indexPath.row];
[cell setNumberOfWordsForFirstLabel:n1 secondLabel:n2];
[cell layoutIfNeeded]; // <- added
return cell;
}
发布于 2016-12-12 22:23:29
当其他类似的解决方案不起作用时,这对我来说是有效的:
override func didMoveToSuperview() {
super.didMoveToSuperview()
layoutIfNeeded()
}
这似乎是一个实际的错误,因为我非常熟悉AutoLayout和如何使用UITableViewAutomaticDimension,但我仍然偶尔会遇到这个问题。我很高兴我终于找到了一些可以作为变通方法的东西。
发布于 2015-05-13 03:01:06
在cellForRowAtIndexPath
中添加[cell layoutIfNeeded]
对于最初滚动出视图的单元格不起作用。
用[cell setNeedsLayout]
作为它的前缀也不会。
您仍然需要将某些单元格滚动到视图中,才能正确调整它们的大小。
这是相当令人沮丧的,因为大多数开发人员都有Dynamic Type,AutoLayout和Self- since正常工作-除了这个恼人的情况。这个bug会影响我所有的“高个子”表视图控制器。
https://stackoverflow.com/questions/25971147
复制相似问题