UIPageViewController检测手势滑动

5

在向左/向右滑动UIPageViewController时,有没有一种方式可以确定平移位置?我一直在尝试实现这一点,但没有成功。我有一个UIPageViewController作为子视图添加到界面上,可以水平左右滑动以切换页面,但是我需要确定我在屏幕上拖动的x,y坐标。

2个回答

5

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

4

我个人的偏好是不太依赖于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)
    //...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接