Search code examples
swiftuiuipageviewcontrollermodal-view

SwiftUI: present modal over PageViewController


I have experienced some problem with UIPageViewController. At some point in its Coordinator the references to UIViewControllers are come invalid. It causes to loose all of the UIPageViewController pages except first one after dismissing modal view.

As completion of basic SwiftUI tutorial Interfacing with UIKit the modal view presentation implemented on tap by featured item. There is github repo.

I have found after modalview dismissed the coordinator in pageViewController delegates looks for initially created UIViewControllers while they are recreated few times. So when I try to scroll over the pages the delegates can't find actual UIViewControllers


        func pageViewController(
            _ pageViewController: UIPageViewController,
            viewControllerAfter viewController: UIViewController) -> UIViewController?
        {
            guard let index = __parent.controllers.firstIndex(of: viewController)__ else {
                return nil
            }

        }

As official documentation said the synchronization of coordinator and UIPageViewController should be UIViewControllerRepresentable responsibility

    /// Updates the presented `UIViewController` (and coordinator) to the latest
    /// configuration.
    func updateUIViewController(_ uiViewController: Self.UIViewControllerType, context: Self.Context)

Have I missed something or is this bug in UIViewControllerRepresentable? How can I use modal view over UIPageViewController without loosing the ability to scroll over pages?


Solution

  • I had a similar issue and I resolved it by calling pageViewController.setViewControllers(_:direction:animated:)

    from the makeUIViewController(context:) function instead of the updateUIViewController(:) function since the former gets only called once.