Get scroll position of UIPageViewController

UIPageViewController scroll doesn't work like normal scrollview and you can't get scrollView.contentOffset like other scrollViews.

so here is a trick to get what's going on when user scrolls :

first you have to find scrollview and set delegate to current viewController like other answers said.

class YourViewController : UIPageViewController {

    var startOffset = CGFloat(0) //define this

    override func viewDidLoad() {
         super.viewDidLoad()

         //from other answers   
         for v in view.subviews{
             if v is UIScrollView {
                 (v as! UIScrollView).delegate = self
             }
         }
     }

    .
    .
    .
}

extension YourViewController : UIScrollViewDelegate{

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

        startOffset = scrollView.contentOffset.x
    }

    public func scrollViewDidScroll(_ scrollView: UIScrollView) {

        var direction = 0 //scroll stopped

        if startOffset < scrollView.contentOffset.x {
            direction = 1 //going right
        }else if startOffset > scrollView.contentOffset.x {
            direction = -1 //going left
        }

        let positionFromStartOfCurrentPage = abs(startOffset - scrollView.contentOffset.x)
        let percent = positionFromStartOfCurrentPage /  self.view.frame.width

        //you can decide what to do with scroll
    }

}

You can search for the UIScrollView inside your UIPageViewController. To do that, you will have to implement the UIScrollViewDelegate.

After that you can get your scrollView:

for v in pageViewController.view.subviews{
    if v.isKindOfClass(UIScrollView){
        (v as UIScrollView).delegate = self
    }
}

After that, you are able to use all the UIScrollViewDelegate-methods and so you can override the scrollViewDidScroll method where you can get the scrollPosition:

func scrollViewDidScroll(scrollView: UIScrollView) {
   //your Code
}

Or if you want a one-liner:

let scrollView = view.subviews.filter { $0 is UIScrollView }.first as! UIScrollView
scrollView.delegate = self

Tags:

Ios

Swift