ios - UINavigationController topViewController 未显示

标签 ios xcode swift uinavigationcontroller storyboard

我正在使用下面的代码尝试更改 UINavigationController 中显示的 viewController:

var mainStoryboard = UIStoryboard(name: "Main", bundle: nil)

var navigationController:UINavigationController = mainStoryboard.instantiateViewControllerWithIdentifier("navController") as UINavigationController
var homeViewController: UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("HomeView") as UIViewController

navigationController.popViewControllerAnimated(false)
navigationController.pushViewController(homeViewController, animated: false)

var topController = navigationController.topViewController as UIViewController
println("homeview id:\(homeViewController.restorationIdentifier)")
println("topview id: \(topController.restorationIdentifier)")  

这是 Storyboard:
enter image description here
第一个问题:为什么当我在这个例子中删除 popViewControllerAnimated 函数调用时,即使我按下 HomeView ,顶部 View 仍然是 LoginView ? (它不是应该是最后推送的 View Controller 吗?)
第二个问题:当我继续调用 popViewControllerAnimated 函数时,我得到了正确的顶部 View (我的顶部 View 现在是预期的 HomeView)但是屏幕上显示的 ViewController 仍然是 loginView。为什么新的 TopViewController 没有出现?
谢谢

最佳答案

问题在于您实例化了一个新的导航 Controller ,而不是访问应用启动时自动实例化的导航 Controller 。而不是这一行,

var navigationController:UINavigationController = mainStoryboard.instantiateViewControllerWithIdentifier("navController") as UINavigationController

你应该用这个,

var navigationController:UINavigationController = self.view.window.rootViewController // it should just be self.window.rootViewController if this code is in the app delegate

关于ios - UINavigationController topViewController 未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219856/

相关文章:

ios - 为什么 CIContext.createCGImage 会导致内存泄漏?

ios - 如何在 macOS Mojave 10.14.6 上运行 Xcode 11.4

ios - 将数据(标签和日期选择器)从我的应用程序发送到提醒应用程序

ios - 比较和匹配数组值

iphone - 如何从一个 View 复制一个字符串并在下一个 View 中显示它?(iphone)

ios - Swift iOS 和 Java Sockets 之间的 TCP 通信

swift - Swift 3.0 中用于 NSMutableSet 的 componentsByString

ios - 如何使用 DispatchGroup 在 for 循环中进行异步调用

ios - Firebase crashlytics 没有告诉我 swift 的确切崩溃问题

ios - 关联类型为类的协议(protocol)的扩展?