Gareth Jones
Gareth Jones

Reputation: 301

UITableView cells added with insertRowsAtIndexPaths are not drawn/laid out correctly

I have a UITableView that's divided into sections, some of which I'm trying to make collapsible - tap on a section's header, and the cells in the section will expand/collapse.

I'm doing this with tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic), inside a self.tableView.beginUpdates() and self.tableView.endUpdates() block.

When opening a section for the first time (i.e. adding rows to the section for the first time), the cells inside aren't laid out properly. Instead of multiline text and a cell whose height expands to fit the required content, I get a one-line cell that's the standard 44pts high whose text is truncated with an ellipsis.

The cells' heights are usually controlled by estimatedHeightForRowAtIndexPath returning UITableViewAutomaticDimension.

The cells seem to get re-drawn and show their correct layout when they are scrolled off screen, or when a section is closed and re-opened.

So is there a way for me to make the cell/section/table redraw itself before the new cells are animated into view?

I've unsuccessfully tried things like self.tableView.reloadData() and reloadRowsAtIndexPaths, but I may not have been using these correctly.

I think I've got the right code, but it's possibly in the wrong place in the "rendering sequence", for want of a better term.

Many thanks!

Upvotes: 2

Views: 477

Answers (2)

Anirudha Mahale
Anirudha Mahale

Reputation: 2596

self.mainTableView.beginUpdates()
    self.mainTableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Fade)
    self.mainTableView.reloadRowsAtIndexPaths(self.mainTableView.indexPathsForVisibleRows!, withRowAnimation: UITableViewRowAnimation.Fade)
    self.mainTableView.endUpdates()

This worked perfect for me.

Upvotes: 0

NikosM
NikosM

Reputation: 1131

I was just having the same problem and was able to fix this by setting an estimatedRowHeight for the tableView. The default value is 0 so setting it to a positive value seems to do the trick:

tableView.estimatedRowHeight = 44.0;

Upvotes: 1

Related Questions