Search code examples
iosswiftuitableviewautolayoutnslayoutconstraint

Ambiguous layout with dynamic tableView height


I have a viewController and I want to have two 1 tableView and 1 childViewController inside it.

  • tableView is non-scrollable with dynamic cell heights. (I'm using a tableView so I can collapse rows)
  • childVC is a scrollable tableView with dynamic cell heights.

my constraints are as:

NSLayoutConstraint.activate([
   tableView.topAnchor.constraint(equalTo: view.topAnchor),
   tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
   tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
   tableView.bottomAnchor.constraint(equalTo: artistVC.view.topAnchor),

])

NSLayoutConstraint.activate([
   artistVC.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
   artistVC.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
   artistVC.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])

When I setup this way, only the childVC shows on the screen. I don’t see the tableView. I want to allow the tableView to expand as much as it needs and then let the childVC be scrollable to the bottom.

  • for the tableView I get: Height and scrollable content size are ambiguous
  • for the childVC’s view I get: Height and vertical positions are ambiguous

However I can't set the height myself as I don't know what the height of the tableViewCell is..

Any suggestions? I've tried changing the content hugging and content Compression Resistance but I didn't find any luck there.


Solution

  • I suggest subclassing UITableView like this:

    class AutomaticHeightTableView: UITableView {
    
      override var intrinsicContentSize: CGSize {
        return contentSize
      }
    
      override func reloadData() {
        super.reloadData()
        invalidateIntrinsicContentSize()
      }
    }
    

    Then in Interface Builder set AutomaticHeightTableView as the class to your table view and the table will try to size itself to fit the content. It will follow any other constraints you placed so make sure the constraints allow it to grow freely.