Embed PageViewController in ScrollView - Programmatically Swift 5

1.2k views Asked by At

I have a PageViewController which shows 4 four view Controllers horizontally,

Can I embed all this viewControllers in a UIScrollView? It would be easier to manage some tasks.

Till now I tried doing this in PageViewController, conforming the PageViewController to UIScrollViewDelegate:

 for view in self.view.subviews {
            if let subView = view as? UIScrollView {
                subView.delegate = self
                subView.isScrollEnabled = true
                subView.bouncesZoom = false
        }
    }

But it actually recognises the scrolling for the single ViewController and not for the entire stack of four VCs. I'd like to have the contentSize of the ScrollView equal to the entire width of all viewControllers.

1

There are 1 answers

0
DonMag On BEST ANSWER

You cannot change a UIPageViewController into a scroll view. It already is a scroll view, but has a lot of built-in functionality for memory-managed paging through view controllers.

If your goal is to put 4 view controllers into a scroll view:

  • create a new (plain) UIViewController
  • add a UIScrollView and constrain it to all 4 sides
  • add a UIStackView (Distribution: Fill Equally) to the scroll view
  • constrain all 4 sides of the stack view to the scroll view's content layout guide
  • constrain its height to the scroll view's frame layout guide height
  • add 4 UIContainerViews to the stack view
  • embed each of your 4 "page" view controllers into the 4 containers
  • constrain the width of the first container to width of scroll view frame layout guide

You now have a full-view UIScrollView where you can scroll back and forth through your 4 "page" view controllers.