Home > database >  Setting Child ViewController Height in ScrollView in Swift
Setting Child ViewController Height in ScrollView in Swift

Time:10-14

I have 2 View Controllers with a ScrollView each (ViewController A & B). I have to add them into a Parent ViewController (ViewController C) as child ViewControllers, one after the other vertically. Child ViewControllers should not scroll independently (ScrollViews should be removed from view hierarchy). Rather, Parent View Controller should have a scrollView, as represented in the picture. How do I achieve this?

enter image description here

My Approach is as below:

Child View Controllers:

  1. Removed scrollView from the child VC view hierarchies.
  2. Add the subview of scrollView directly into main view of the VC.

Parent View Controller:

  1. Added child VCs to the parent VC.
  2. Created two containers with a fixed frame in Parent VC.
  3. Added child VC's View to the two container views as subviews. (created in #2)

The problem is the fixed frame of the two containers. How can I set their height equal to their respective child's view? Also how do I update the parent scrollView's content Size?

CodePudding user response:

Add a UIStackview to the scrollview of VC C, add an arbitraty height constraint to it with a low priority. Then add the views of VC A and B to the stackview, if these views have an intrinsic size (induced by constraints) the stackview will scale automatically, allowing for scrolling in VC C.

  • Related