Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scroll position of UIPageViewController

Tags:

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.

like image 405
Unome Avatar asked Jan 30 '15 17:01

Unome


1 Answers

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 
like image 54
Christian Avatar answered Oct 06 '22 14:10

Christian