添加页面时 UIPageViewController 崩溃

Ami*_*elS 0 ios uipageviewcontroller swift

在我正在开发的 iOS 11 应用程序中(使用 Swift 4),我需要将页面动态添加到UIPageViewController. 但是,在某些情况下,我会收到以下崩溃错误 ( NSInternalInconsistencyException):

2017-11-27 14:55:54.787260+0000 MyApp[380:79434] *** Assertion failure in -[UIPageViewController _flushViewController:animated:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3698.21.8/UIPageViewController.m:2124
2017-11-27 14:55:54.791022+0000 MyApp[380:79434] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Don't know about flushed view <UIView: 0x12dd48ac0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x1c003c280>>'
Run Code Online (Sandbox Code Playgroud)

我对 iOS 开发很陌生,所以如果答案很明显,我很抱歉,但我很难找到崩溃的根本原因。记录的消息也不是很有帮助...

这是我用来添加页面的代码:

//Inflate the view controller
let viewController = newViewController(param: someParam )

//Add it to the view controllers pool
viewControllersOrdered.insert(viewController, at: getInsertionIndex(param: someOtherParam) )

//Add it to the pageViewController
pageViewController.setViewControllers([viewController], direction: .forward, animated: false, completion: nil)

//Force cache to be cleared
pageViewController.dataSource = nil;
pageViewController.dataSource = self;
Run Code Online (Sandbox Code Playgroud)

getInsertionIndex功能正常工作,这不是崩溃的根源。

mat*_*att 6

在我正在开发的 iOS 11 应用程序中(使用 Swift 4),我需要将页面动态添加到 UIPageViewController。

听起来您的意思是:在用户实际尝试“翻页”之前,您不知道下一个/上一个视图控制器将是什么。在这种情况下,滚动 UIPageViewController 不太适合您的架构(因为,正如您已经发现的那样,它会预缓存下一页和上一页)。你有两个选择:

  • 使用页面卷曲 UIPageViewController。它不会预先缓存其页面,因此在用户实际要求翻页之前,不会要求您做出决定。

  • 根本不要使用 UIPageViewController;使用分页水平滚动视图并自己管理内容视图。

此外,如果您使用的是 UIPageViewController,在任何情况下您都不应该持有保留的子视图控制器列表。这就是 UIPageViewController 的工作。你的工作只是提供下一个或上一个视图控制器,你应该按需创建,而不是其他时间,并将其释放到 UIPageViewController 的唯一控件中。