Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIPageViewController detecting pan gestures

Is there a way to determine the panning location of a UIPageViewController while sliding left/right? I have been trying to accomplish this but its not working. I have a UIPageViewController added as a subview and i can slide it horizontally left/right to switch between pages however i need to determine the x,y coordinates of where I am panning on the screen.

like image 323
1337holiday Avatar asked Feb 10 '23 17:02

1337holiday


2 Answers

I figured out how to do this. Basically a UIPageViewController uses UIScrollViews as its subviews. I created a loop and set all the subviews that are UIScrollViews and assigned their delegates to my ViewController.

/**
 *  Set the UIScrollViews that are part of the UIPageViewController to delegate to this class,
 *  that way we can know when the user is panning left/right
 */
-(void)initializeScrollViewDelegates
{
    UIScrollView *pageScrollView;
    for (UIView* view in self.pageViewController.view.subviews){
        if([view isKindOfClass:[UIScrollView class]])
        {
            pageScrollView = (UIScrollView *)view;
            pageScrollView.delegate = self;
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"Im scrolling, yay!");
}
like image 90
1337holiday Avatar answered Feb 13 '23 07:02

1337holiday


My personal preference is not to rely too much on the internal structure of the PageViewController because it can be changed later which will break your code, unbeknownst to you.

My solution is to use a pan gesture recogniser. Inside viewDidLoad, add the following:

let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handler))
gestureRecognizer.delegate = yourDelegate
view.addGestureRecognizer(gestureRecognizer)

Inside your yourDelegate's definition, you should implement the following method to allow your gesture recogniser to process the touches

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

Now, you should be able to access the X/Y location of the user's touches:

func handler(_ sender: UIPanGestureRecognizer) {
    let totalTranslation = sender.translation(in: view)
    //...
}
like image 36
Jason Avatar answered Feb 13 '23 08:02

Jason