UINavigationController topViewController没有显示出来

时间:2014-12-01 00:05:43

标签: 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)")  

这是故事板:
enter image description here
第一个问题:为什么当我在这个例子中删除popViewControllerAnimated函数调用时,即使我按下HomeView,顶视图仍然是LoginView? (它不应该是最后推送的视图控制器吗?)
第二个问题:当我保持popViewControllerAnimated函数调用时,我得到了正确的顶视图(我的topView现在是预期的HomeView),但屏幕上显示的ViewController仍然是loginView。为什么新的TopViewController不显示呢? 感谢

1 个答案:

答案 0 :(得分:2)

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

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
相关问题