Monday, March 20, 2017

Swift 3.0 - PageView Controller

The tutorial given in the reference link is awesome one. Few notes mainly are

class TutorialPageViewController: UIPageViewController {

private(set) lazy var orderedViewControllers: [UIViewController] = {
    return [self.newColoredViewController("Green"),
            self.newColoredViewController("Red"),
            self.newColoredViewController("Blue")]
}()

private func newColoredViewController(color: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil) .
    instantiateViewControllerWithIdentifier("\(color)ViewController")
}    

    override func viewDidLoad() {
    super.viewDidLoad()
    
    dataSource = self
    
    if let firstViewController = orderedViewControllers.first {
        setViewControllers([firstViewController],
                           direction: .Forward,
                           animated: true,
                           completion: nil)
    }
    }

}

Have the below two methods as delegates

func pageViewController(pageViewController: UIPageViewController,
    viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
            return nil
        }
        
        let previousIndex = viewControllerIndex - 1
        
        guard previousIndex >= 0 else {
            return nil
        }
        
        guard orderedViewControllers.count > previousIndex else {
            return nil
        }
        
        return orderedViewControllers[previousIndex]
}

func pageViewController(pageViewController: UIPageViewController,
    viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
            return nil
        }
        
        let nextIndex = viewControllerIndex + 1
        let orderedViewControllersCount = orderedViewControllers.count

        guard orderedViewControllersCount != nextIndex else {
            return nil
        }
        
        guard orderedViewControllersCount > nextIndex else {
            return nil
        }
        
        return orderedViewControllers[nextIndex]
}

references:
https://spin.atomicobject.com/2015/12/23/swift-uipageviewcontroller-tutorial/

No comments:

Post a Comment