Determining the height of a child VC's content from the container VC, and using it to size the container vc?

557 Views Asked by At

I have a container view controller that can hold any generic ViewController. If I use a stack view, or any other view (without a scroll view), I can accurately calculate the size in my container initializer using the following:

let targetSize = CGSize(width: contentVC.view.bounds.width)
let preferredSize = contentViewcontroller.view.systemLayoutSizeFitting(targetSize)
self.containerHeight = preferredSize.height

However, this stops working once I'm dealing with a table view inside the child vc. The height is returned as zero. What's the best way to handle it without having to do much / any work on the child vc side?

NOTE: I'm using auto layout (SnapKit), to pin and layout my views.

1

There are 1 best solutions below

0
Vitalii Shvetsov On

It is because you are trying to access UIView (UITableView) when it was only created and added as a subview, but it hasn't been drawn yet. You have to force draw it.

self.view.setNeedsLayout()
self.view.layoutIfNeeded()

For the UIViewController you access it in viewDidLoad(), and it's the moment when the size is known