Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect current page of UIPageViewController

I want to detect the current page in order to modify a button's title while the last page is showing and re-modify every time the user swipes back from the last to the second to last page.

Now these are my delegate methods and my array of ViewControllers:

lazy var VCArr: [UIViewController] = {
    let firstVC = self.storyboard!.instantiateViewController(withIdentifier: "FirstTutorialPage")
    let secondVC = self.storyboard!.instantiateViewController(withIdentifier: "SecondTutorialPage")
    let thirdVC = self.storyboard!.instantiateViewController(withIdentifier: "ThirdTutorialPage")
    let fourthVC = self.storyboard!.instantiateViewController(withIdentifier: "FourthTutorialPage")
    return [firstVC, secondVC, thirdVC, fourthVC]
}()

delegate methods

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

    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let previousIndex = viewControllerIndex - 1

    guard previousIndex >= 0 else {
        return nil
    }

    guard self.VCArr.count > previousIndex else {
        return nil
    }

    return self.VCArr[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = self.VCArr.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1

    guard nextIndex < self.VCArr.count else {
        return nil
    }

    guard self.VCArr.count > nextIndex else {
        return nil
    }

    return self.VCArr[nextIndex]
}

Can someone help me detect with accuracy the last page shown? I tried some methods but everyone of them showed me the wrong index. Those methods detected the last index while showing the second to last page.

Thanks to all.

like image 992
Elia Crocetta Avatar asked Aug 07 '17 18:08

Elia Crocetta


1 Answers

My solution consist in implementing the function pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:) of the UIPageViewControllerDelegate and doing the following:

if completed {
    if let currentViewController = pageViewController.viewControllers?.first,
    let index = pages.index(of: currentViewController) {
        currentIndex = index
    }
}

where pages is a property of my page view controller where I store all my view controllers to be presented and currentIndex is a property to keep track of the index of the current page (aka view controller) in order to use it in other parts of my code.

like image 60
Francesco Avatar answered Nov 09 '22 01:11

Francesco