Unome Unome - 7 months ago 208
Swift Question

Get scroll position of UIPageViewController

I am using a

UIPageViewController
, and I need to get the scroll position of the ViewController as the users swipe so I can partially fade some assets while the view is transitioning to the next
UIViewController
.

The delegate and datasource methods of
UIPageViewController
don't seem to provide any access to this, and internally I'm assuming that the
UIPageViewController
must be using a scroll view somewhere, but it doesn't seem to directly subclass it so I'm not able to call

func scrollViewDidScroll(scrollView: UIScrollView) {

}


I've seen some other posts suggestion to grab a reference to the
pageViewController!.view.subviews
and then the first index is a scrollView, but this seems very hacky. I'm wondering if there is a more standard way to handle this.

Answer

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
}