【问题标题】:UIPageViewController where to implement setViewControllers(..:) methodUIPageViewController 在哪里实现 setViewControllers(..:) 方法
【发布时间】:2020-06-08 03:14:33
【问题描述】:

所以我有一个 UIPageViewController,如果设备处于横向状态,我希望将 spinLocation 实现为 .mid,而对于纵向则实现 .min,因此在横向显示两个控制器,一个在纵向显示。

在页面视图控制器委托中我实现了这个功能:

func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation {
    if orientation == .landscapeLeft || orientation == .landscapeRight {
        return .mid
    } else {
        return .min
    }
}

在我的 UIPageViewController 类中,设置视图控制器我有这个功能:

func setControllers() {
    var controllers: [UIViewController] = [controller1]
    if spineLocation == .mid {
        controllers.append(controller2)
    }
    setViewControllers(controllers, direction: .forward, animated: true, completion: nil)
}

我的问题是我不知道该放在哪里,我试过了:

  1. viewDidLoad(在设置 pageController 委托之前)
  2. viewDidLoad(设置 pageController 委托后)
  3. viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
  4. didRotate(来自 fromInterfaceOrientation: UIInterfaceOrientation)
  5. willRotate(toInterfaceOrientation: UIInterfaceOrientation, 持续时间: TimeInterval)

视图在纵向模式下正确显示,但是当我启动或将设备转为横向时,应用程序崩溃:

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“提供的视图控制器的数量 (1) 与请求的脊椎位置 (UIPageViewControllerSpineLocationMid) 所需的数量 (2) 不匹配”


【问题讨论】:

    标签: swift uiinterfaceorientation uipagecontrol


    【解决方案1】:

    我通过以下方式修复它: 添加 spinLocation 作为函数 setControllers 的参数:

    func setControllers(forSpineLocation location: SpineLocation) {
    var controllers: [UIViewController] = [controller1]
    if location == .mid {
        controllers.append(controller2)
    }
    setViewControllers(controllers, direction: .forward, animated: true, completion: nil)
    

    }

    并且通过在 viewDidLoad 和 pageViewController(_ pageViewController: UIPageViewController, spinLocationFor orientation: UIInterfaceOrientation) 上实现它:

    override func viewDidLoad() {
        super.viewDidLoad()
        setControllers(withLocation: spineLocation)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation {
        var location = SpineLocation.min
        if orientation == .landscapeLeft || orientation == .landscapeRight {
            location = .mid
        }
        setControllers(withLocation: location)
        return location
    }
    

    我不知道这是正确还是最好的方法,但它确实有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 2012-03-05
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多