Search code examples
iosswiftuipageviewcontroller

Detect change in page/completion of animation to another page in UIPageViewController


I have the following function which I would like to call whenever the user swipes from one page to another (vertical paging):

func sendNotification (){

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "stopVideo"), object: nil)
    print("called")

}

Currently, the function is called whenever the pageAfter or -before is created so to say. The function used to "create" the next/previous page looks like this (in this case it's viewControllerAfter):

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {

    let currentIndexString  = (viewController as! MyViewController).index
    let currentIndex        = indec.index(of: currentIndexString!)

    //set if so that next page
    if currentIndex! < indec.count - 1 {

        let myViewController = MyViewController()

        myViewController.index            = indec[currentIndex! + 1]

        sendNotification() //function is called 

        return myViewController

    }

    return nil

}

Since the UIPageViewController somewhat prepares the following pages and going back to the previous page also doesn't call the function (as the view controller does not need to be "created") I do not get the result I want. I was wondering if there is a function in which I can call sendNotification() on completion of the animation. I found a lot of questions regarding jumping to another page but none concerning my problem. I'd really appreciate your help!


Solution

  • You can use the UIPageViewControllerDelegate Functions

    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController])
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    

    As the name of these functions say, the first one will be called, when the user swipes to another page of your PageViewController.

    The Second one will be called, when the Transition has completed, which means the user sees the next page after the animation.

    In both you can check for changes between the pages.

    Also do not forget to check the completed variable of the second function. If the user starts swiping and then does not go to the next page (cause he releases the finger before it or similar) it is false and you do not have your new ViewController.

    The array previousViewControllers holds the recently shown controllers where previousViewControllers[0] is probably the one shown before.

    For more Information look up the documentation