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.
This worked for me when other similar solutions did not:
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.
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
andViewWillAppear
methods. This solved my problem.For 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 usingUITableViewAutomaticDimension
worked as expected.I ran into this issue and fixed it by moving my view/label initialization code FROM
tableView(willDisplay cell:)
TOtableView(cellForRowAt:)
.