0

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.

KingPolygon
  • 4,753
  • 7
  • 43
  • 72
  • A table view has no intrinsic size, so the question makes no sense. – matt Aug 26 '20 at 20:30
  • Yes, but it has a content size. I've managed to get it to layout properly by using a protocol which provides the container with a height property. I can essentially set it to tableView.contentSize.height in the child VC and everything works. What I'd really like is to have the child vc update the container vc if there's a change (an item in the table view is removed). Trying to figure out the best way to do this. – KingPolygon Aug 26 '20 at 20:39
  • What happens if you have 50 rows in your "child VC" table view? Will your container height work if the table view's contentSize.height is, say, 3000? – DonMag Aug 26 '20 at 20:45
  • Hhaha good question right now we aren't really accounting for that since we don't expect more than say 3-5 rows, but ideally the container view (drawer) would just mimic Uber's behavior of going full screen. – KingPolygon Aug 26 '20 at 20:50
  • 1
    @KingPolygon - well, then, I'd recommend building your design and functionality with that in mind. Using a table view for 3-5 rows (which could just as easily be done with 3-5 instances of a custom view in a stack view, for example) is a very different prospect than "it might have 10, 20, 50 rows." – DonMag Aug 26 '20 at 21:07
  • Fair point! Agreed – KingPolygon Aug 26 '20 at 22:31

1 Answers1

0

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

Vitalii Shvetsov
  • 404
  • 2
  • 11