使用 NavigationViewController 导航

Navigate with NavigationViewController

我想知道如何使用 NavigationController 在应用程序中正确导航,而不是每次调用它时都实例化 ViewController 例如:

在所有已知的应用程序中,例如 Instagram,当您单击工具栏项目时,您会访问一个 viewController,但此状态已保存,如果您在照片上,它仍然在这张照片在你进入设置后,post 照片等。在我的应用程序中,我的 NavigationController 每次我想访问它时都会实例化一个新的 ViewController,当你在 ViewDidLoad 中加载数据时会消耗时间例如。

有人可以帮助我吗?

如果您不想创建新控制器 - 请不要创建它!

创建您的控制器一次,然后重新使用它们。例如,您可以将控制器声明为单例:

let vc1 = MyViewController1()
let vc2 = MyViewController1()
let vc3 = MyViewController1()

并且当您需要推送某些控制器时,不要创建新控制器而是重用已经创建的控制器:

navigationVC.pushViewController(vc2, animated: true)

如果您尝试推送已在导航堆栈中的控制器,UINavigationController 将抛出错误。所以你必须先从导航堆栈中删除它:

// vc2 - is a controller that could be in the navigation stack and should be pushed once more
var controllers = navigationVC.viewControllers
if let index = controllers.indexOf(vc2){
    controllers.removeAtIndex(index)
}
navigationVC.setViewControllers(controllers, animated: false)

然后你可以照常推送vc2。如果在您的应用程序中有可能,您还应该检查是否应在 vc2 之后立即推送 vc2