iosswiftuitableviewuitableviewautomaticdimension

Is it possible to use self sizing cells within self sizing cells?


I want to have self sizing cells within a tableview with self sizing cells. But on first initialisation some cells are not correct. After a scroll to the bottom and the cells will display again the cell size is correct. In the screenshot you can see that the top 2 cells have a white space at the bottom and the third one doesn't. They should all look like the third one.

enter image description here

This is the issue in my main project. Screenshot


Solution

  • The problem with automatically sizing cells inside automatically sized cells is a bit tricky because you have to understand how it works. UITableView works with estimates most of the time. It usually does not calculate the contentSize precisely because to calculate it precisely, it has to first instantiate every cell, layout it and then calculate its size.

    The precise values are calculated only for cells that are displayed (visible in current scroll frame).

    The tricky part is that the inner cells (inside your outer cell) are not displayed until the outer cell is displayed therefore the outer cell does not have size calculated correctly. Also note that UITableView does not automatically update cell heights unless explicitly said to do so.

    The solution, if you really have to do this, is to calculate the height of the outer cell correctly before it is displayed and manually set a height constraint.

    If you know the height (from data source), it's easy. If you actually need to calculate the height of the inner table, you can do something like this:

    // make the table high enough to display all cells
    innerTableHeightConstraint.constant = 2000
    // reload table
    innerTable.reloadData()
    // force layout
    innerTable.layoutIfNeeded()
    // now the contentSize is correctly calculated
    innerTableHeightConstraint.constant = innerTable.contentSize.height
    

    The whole concept is tricky and ideally you should prefer using UICollectionView or table sections. When you are using inner table views, there won't be any cell reuse for the inner tables and your performance will suffer.