UITableView dynamic cell heights only correct afte

2019-01-10 04:39发布

I have a UITableView with a custom UITableViewCell defined in a storyboard using auto layout. The cell has several multiline UILabels.

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.

Sample project: Top of table view from sample project on first load. Sample project: Same cells after scrolling down and back up.

22条回答
干净又极端
2楼-- · 2019-01-10 05:06

This worked for me when other similar solutions did not:

override func didMoveToSuperview() {
    super.didMoveToSuperview()
    layoutIfNeeded()
}

This seems like an actual bug since I am very familiar with AutoLayout and how to use UITableViewAutomaticDimension, however I still occasionally come across this issue. I'm glad I finally found something that works as a workaround.

查看更多
Animai°情兽
3楼-- · 2019-01-10 05:06

I tried all of the solutions in this page but unchecking use size classes then checking it again solved my problem.

Edit: Unchecking size classes causes a lot of problems on storyboard so I tried another solution. I populated tableView in view controller's ViewDidLoad and ViewWillAppear methods. This solved my problem.

查看更多
4楼-- · 2019-01-10 05:06

Attatching screenshot for your referanceFor me none of these approaches worked, but I discovered that the label had an explicit Preferred Width set in Interface Builder. Removing that (unchecking "Explicit") and then using UITableViewAutomaticDimension worked as expected.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-10 05:07

I ran into this issue and fixed it by moving my view/label initialization code FROM tableView(willDisplay cell:) TO tableView(cellForRowAt:).

查看更多
登录 后发表回答