nebkat
nebkat

Reputation: 8565

Nested UITableView of variable height in UITableViewCell + UITableViewAutomaticDimension

I have a UITableView in which the cells contain an ImageView and a nested UITableView. The nested table can contain a variable number of cells and therefore has a variable height (and it isn't scrollable).

I am trying to set the parent cell height to be equal to the height of the image and the nested table view with UITableViewAutomaticDimension but it is only extending as far as the image, probably because the table view starts with a height of 0 and is populated after it is created in the parent cell.

How can I make the parent table cells be the same height as their content? I have already set the constraints between the cell content view and the image/nested table.

Upvotes: 4

Views: 3391

Answers (2)

Fitsyu
Fitsyu

Reputation: 900

Done similar thing today. Here is what worked for me.

Neither need to set UITableViewAutomaticDimension nor setting tableView.rowHeight property.

First disable scrolling in inner table view.

innerTableView.isScrollEnabled = false

or if you designed it in storyboard, you can uncheck scrolling enabled property.

scrolling disabled

Assume for every cell:

  • image height = 100
  • inner table view's cell height = 30

Then calculate the cell's height is equal to image height plus nested table view's cells count multiplied by cell size in tableView(tableView:heightForRowAt) e.g:

// constant
let imgHeight = 100
let innerCellHeight = 30

// inner cell count
let dataSource = dataSources[indexPath.row]
let innerCellsCount = dataSource.items.count


return CGFloat( imgHeight + ( innerCellsCount * innerCellHeight ) )

also implement tableView(tableView:estimatedHeightForRowAt) function so scrolling will be smoother e.g If inner table view might be contains no cells simply return image height.

Upvotes: -1

anaghaajith27
anaghaajith27

Reputation: 61

I faced a similar issue while trying to implement nested tableViews. I found two solutions to this problem.

  1. Calculating the height of the innerTableView and setting the rowHeight of the outerTableView to it by executing the following in it's cellForRowAtIndexPath

rowHeight = cell.innerTableView.contentSize.height

return rowHeight in tableView:estimatedHeightForRowAtIndexPath and tableView:heightForRowAtIndexPath

This worked for me to set the outerTableView's cellHeight depending on inner content.

  1. Check this tutorial out. http://vuta.info/dynamic-uitableviews-height-with-auto-layout-in-swift/

Upvotes: 3

Related Questions