Disable UIPageViewController bounce

前端 未结 13 2430
离开以前
离开以前 2020-11-27 04:08

Searched a lot for this one, but couldn\'t find a proper solution yet.

Is it possible to disable the bounce effect of a UIPageViewController and still

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 04:38

    The only working solution, 2020

    Below is a complete solution that, unlike with other answers, doesn't require you to write/test your own code for tracking the index of the currently displayed page.

    Assuming that your pages are stored in sourcePageViewControllers immutable array and after you've created your UIPageViewController as myPageViewController:

    let scrollView = myPageViewController.view.subviews.compactMap({ $0 as? UIScrollView }).first!
    scrollView.delegate = 
    

    And then:

    extension YourScrollViewDelegateClass: UIScrollViewDelegate {
    
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            guard sourcePageViewControllers.count > 1 else {
                scrollView.isScrollEnabled = false
                return
            }
            
            guard let viewControllers = myPageViewController.viewControllers, viewControllers.count != 0 else { return }
    
            let baseRecord =
                viewControllers
                .map { [superview = myPageViewController.view!] viewController -> (viewController: UIViewController, originX: CGFloat) in
                    let originX = superview.convert(viewController.view.bounds.origin, from: viewController.view).x
                    return (viewController: viewController, originX: originX)
                }
                .sorted(by: { $0.originX < $1.originX })
                .first!
    
            guard let baseIndex = sourcePageViewControllers.firstIndex(of: baseRecord.viewController) else { return }
            let baseViewControllerOffsetXRatio = -baseRecord.originX/scrollView.bounds.width
    
            let progress = (CGFloat(baseIndex) + baseViewControllerOffsetXRatio)/CGFloat(sourcePageViewControllers.count - 1)
            if !(0...1 ~= progress) {
                scrollView.isScrollEnabled = false
                scrollView.isScrollEnabled = true
            }
        }
    
    }
    

提交回复
热议问题