我正在编写一个应用程序,我们在用户第一次打开应用程序时启动演练。最后,我们要求用户填写一些细节,为此我希望他按一个按钮重定向到设置页面。
问题是,此页面位于导航控制器的一个级别(从登录页面)。就目前而言,我可以正确地实例化登录页面,但重定向到设置页面永远不会发生。
let mainView = self.storyboard?.instantiateViewControllerWithIdentifier("NavCtrl")
self.presentViewController(mainView!, animated: false, completion: nil)
// the above works correctly and sends us to the landing screen
// (rootView of the navigation controller)
// the following lines never have any effect though
let settingsView = self.storyboard?.instantiateViewControllerWithIdentifier("Settings View")
self.navigationController?.pushViewController(settingsView!, animated: false)
我认为这是因为我试图在故事板有时间渗透第一个或第二个视图之前调用.pushViewController
。
所以我有几个问题:
先谢谢你们
答案 0 :(得分:2)
好的,感谢@Leonardo向我展示了正确的方向!
我通过在appDelegate中执行以下操作解决了这个问题:
/*
* Override window root view and set it to a newly initialized one
* view: StoryboardID of view to display
* navigateTo: if true, set the root view to NavCtrl and then navigate to the desired view
*/
func setWindowViewTo(view: String, navigateTo: Bool) {
//initalize storyboard & window programmatically
window = UIWindow.init(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
//if true, navigate from landing page to specified view through navigationController
if(navigateTo) {
//instantiate the navigation controller
let navCtrl = storyboard.instantiateViewControllerWithIdentifier("NavCtrl") as! UINavigationController
//instantiate the landing page & the page we wish to navigate to
let landingView = storyboard.instantiateViewControllerWithIdentifier("Main View")
let vc = storyboard.instantiateViewControllerWithIdentifier(view)
//manually set the navigation stack to landing view + view to navigate to
navCtrl.setViewControllers([landingView, vc], animated: false)
//replace the rootViewController to the navigation controller
window!.rootViewController = navCtrl
//make it work
window!.makeKeyAndVisible()
} else {
window!.rootViewController = storyboard.instantiateViewControllerWithIdentifier(view)
window!.makeKeyAndVisible()
}
}
重要的一步是在使用as! UINavigationController
方法实例化NavigationController时确实强制转发storyboard.instantiateViewControllerWithIdentifier()
。
然后,只需要正确实例化所需导航堆栈的视图,最后调用navCtrl.setViewControllers([view1, view2], animate: false)
。
感谢大家的帮助!
答案 1 :(得分:1)
您可以使用- setViewControllers:animated:
方法设置UINavigationController
但我不认为这是你的问题,如果我正确地取消你的代码,它应该是
//This is the navigation controller
if let mainView = self.storyboard?.instantiateViewControllerWithIdentifier("NavCtrl"){
//Nav being modally presented
self.presentViewController(mainView, animated: false, completion: nil)
// Instantiate the settings view
if let settingsView = self.storyboard?.instantiateViewControllerWithIdentifier("Settings View"){
//Push it to the navigation controller presented
mainView.pushViewController(settingsView, animated: false)
}
else{
//Can't Instantiate, deal with error
}
}
else{
//Can't Instantiate, deal with error
}