UITableView的动态单元格高度一些滚动后唯一正确 [英] UITableView dynamic cell heights only correct after some scrolling
问题描述
我有一个的UITableView
使用自定义的的UITableViewCell
在使用自动布局的故事板定义。小区有几个多行 UILabels
。
I have a UITableView
with a custom UITableViewCell
defined in a storyboard using auto layout. The cell has several multiline UILabels
.
的的UITableView
似乎正确地计算单元格的高度,但在最初的几个细胞高度不正确的标签之间进行分配。
滚动位后,一切正常(即使是最初的不正确的细胞)。
The UITableView
appears to properly calculate cell heights, but for the first few cells that height isn't properly divided between the labels.
After scrolling a bit, everything works as expected (even the cells that were initially incorrect).
- (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;
}
有什么,我可能会丢失,这是造成自动布局没有能够完成其工作第几次了?
Is there anything that I might be missing, that is causing auto layout not to be able to do its job the first few times?
我创建这表明此行为的示例项目。
I've created a sample project which demonstrates this behaviour.
推荐答案
我不知道这是在返回前明确记载或没有,但加入 [单元layoutIfNeeded]
电池解决您的问题。
I don't know this is clearly documented or not, but adding [cell layoutIfNeeded]
before returning cell solves your problem.
- (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;
}
这篇关于UITableView的动态单元格高度一些滚动后唯一正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!