【发布时间】:2018-02-20 09:01:57
【问题描述】:
我有一个使用 Swift 3.1 编写的应用,使用 Xcode 8.3.3。
我目前正在尝试实施状态保存/恢复。
为此,我在AppDelegate.swift 中实现了shouldSaveApplicationState 和willFinishLaunchingWithOptions 方法并设置为返回true:
// AppDelegate.swift
// STATE RESTORATION CALLBACKS
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
debug_print(this: "shouldSaveApplicationState")
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
debug_print(this: "shouldRestoreApplicationState")
restoringState = true
return true
}
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
debug_print(this: "willFinishLaunchingWithOptions")
return true
}
我还为所有涉及的视图控制器和导航控制器提供了恢复 ID。
我正在使用第 3 方库来处理侧抽屉导航容器 (https://github.com/sascha/DrawerController)。初始视图控制器在 didFinishLaunchingWithOptions 方法中以编程方式设置,见下文。
// AppDelegate.swift
var centerContainer: DrawerController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let centerViewController = mainStoryboard.instantiateViewController(withIdentifier: "RootViewControllerNav") as! UINavigationController
let leftViewController = mainStoryboard.instantiateViewController(withIdentifier: "SideDrawerViewController") as! UITableViewController
centerContainer = DrawerController(centerViewController: centerViewController, leftDrawerViewController: leftViewController)
centerContainer?.restorationIdentifier = "DrawerControllerView"
window = UIWindow(frame: UIScreen.main.bounds)
window?.restorationIdentifier = "MainWindow"
window?.rootViewController = centerContainer
window?.makeKeyAndVisible()
return true
}
当应用程序打开并尝试恢复状态时,它会暂时显示正确的视图控制器(应用程序关闭之前的最后一个控制器),然后一旦应用程序变为活动状态,它就会恢复为初始视图控制器。
例如,会发生以下情况:
- 打开应用程序通过侧边菜单导航到“设置”视图
- 导航到主屏幕
- 停止运行 xcode 并重新启动
- 应用将打开显示设置视图,然后返回主视图
谁能告诉我是什么原因造成的,或者我哪里出错了?如果您需要更多代码示例,请告诉我。
【问题讨论】:
-
你还需要在想要恢复的Controller中实现
static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? -
感谢@Lamar,我实施了您建议的方法并设法让它发挥作用。
-
欢迎您。我认为你应该在你的问题中添加你的答案,这样你就可以帮助其他人解决同样的问题:)
标签: ios iphone swift swift3 xcode8