首页 > 解决方案 > Swift UIPageViewController - 用于请求的脊椎位置 (UIPageViewControllerSpineLocationMin)

问题描述

在这里,我以编程方式创建了 UIPageViewController当我将多个 ViewController 加载UIPageViewController 时。应用程序崩溃。

在下面检查我的代码。

class PageVC: UIPageViewController {
    
    let colors = [UIColor.green, UIColor.red, UIColor.blue, UIColor.black]

    var pages: [UIViewController] = []
    
    override var spineLocation: UIPageViewController.SpineLocation {
        return .min
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.isDoubleSided = true
        
        colors.forEach({
            let page = UIViewController()
            page.view.backgroundColor = $0
            pages.append(page)
        })
        
        self.view.backgroundColor = UIColor.red
        
        self.setViewControllers(pages, direction: UIPageViewController.NavigationDirection.forward, animated: true, completion: nil)
    }
}

得到如下错误。

在此处输入图像描述

帮我解决这个问题。

标签: iosuikituipageviewcontrollerswift5xcode12

解决方案


我从另一个角度面临同样的问题。我试图从options初始化UIPageViewController. 在 Apple 文档之后,我尝试将首选脊椎位置包装成一个NSNumber并将其设置为spineLocation选项字典中键的值,但应用程序总是崩溃。不知道为什么...

实际上,我知道以编程方式更改脊椎位置的唯一方法是在委托方法中返回所选的一个spineLocationFor orientation。您必须创建另一个 ViewController 并将自定义 PageViewController 添加为子项。我知道这不是您问题的确切答案,但希望对您有所帮助。通过代码,使用 UIPageViewController:

class ViewController: UIViewController {

private var pageController: UIPageViewController?

override func viewDidLoad() {
    super.viewDidLoad()
    setupPageController()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    pageController?.view.frame = CGRect(x: 0,
                                        y: 0,
                                        width: self.view.frame.width,
                                        height: self.view.frame.height)
}

private func setupPageController() {
    self.pageController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
    self.pageController?.dataSource = self
    self.pageController?.delegate = self
    self.addChild(self.pageController!)
    self.view.addSubview(self.pageController!.view)

    self.pageController?.setViewControllers([UIViewController()], direction: .forward, animated: true, completion: nil)
            
    self.pageController?.didMove(toParent: self)
}
}

.

extension ViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {

func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation {

    // handle orientation cases if needed
    // assuming you only support landscape:

    let initialVC = UIViewController()
    let initialVC2 = UIViewController()
    self.pageController?.setViewControllers([initialVC, initialVC2], direction: .forward, animated: true, completion: nil)
    pageController?.isDoubleSided = true
    return .mid
    }
}

推荐阅读