UIPageViewController 检测平移手势

UIPageViewController detecting pan gestures

有没有办法在滑动时确定 UIPageViewController 的平移位置left/right?我一直在努力实现这一点,但它没有用。我添加了一个 UIPageViewController 作为子视图,我可以水平滑动它 left/right 以在页面之间切换,但是我需要确定我在屏幕上平移的位置的 x、y 坐标。

我知道怎么做了。基本上 UIPageViewController 使用 UIScrollViews 作为它的子视图。我创建了一个循环并设置了所有的 UIScrollView 子视图,并将它们的委托分配给了我的 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!");
}

我个人的偏好是不要过分依赖 PageViewController 的内部结构,因为它可以在以后更改,这会在您不知情的情况下破坏您的代码。

我的解决方案是使用平移手势识别器。在 viewDidLoad 内,添加以下内容:

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

在您的 yourDelegate 定义中,您应该实现以下方法以允许您的手势识别器处理触摸

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

现在,您应该能够访问用户触摸的 X/Y 位置:

func handler(_ sender: UIPanGestureRecognizer) {
    let totalTranslation = sender.translation(in: view)
    //...
}