我在 appDelegate
中将我的初始 ViewController 设置为 rootViewController
因为我不使用 Storyboard。看起来像这样:
var window: UIWindow?
var mainNavigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.mainNavigationController = UINavigationController()
var mainController: UIViewController? = TineLineViewController()
self.mainNavigationController!.pushViewController(mainController!, animated: true)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = mainController
self.window!.makeKeyAndVisible()
...
...
我的应用程序正在运行并且我的 TineLineViewController
出现了。
我在这个类中有一个调用此方法的 UIButton:
func postLeft(_sender: AnyObject?)
{
println("go to secound view..")
let secondViewController = PostCreateController()
let appDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
self.navigationController?.presentViewController(secondViewController, animated: true, completion: nil)
appDelegate.window?.rootViewController = secondViewController
}
这样一来,如果我按下按钮,屏幕就会改变,我的 secondViewController
就会出现,没有动画......
如果我尝试以这种方式更改 View :
self.navigationController?.pushViewController(secondViewController, animated: true)
它仍然没有任何动画,在 secoundViewController
出现后我的应用程序崩溃并显示此消息:
* 由于未捕获的异常“UIViewControllerHierarchyInconsistency”而终止应用程序,原因:“将 Root View Controller 添加为 View Controller 的 subview :” * 首先抛出调用栈: (
我不知道这是否是在 appDelagate
中设置我的 rootviewController
类的最佳方式,以及为什么不将此行添加到我的 potLeft 函数就无法导航:
appDelegate.window?.rootViewController = secondViewController
如果没有这一行,我可以在我的应用程序控制台中看到调用了 secondViewController
viewDidLoad
方法,但 Controller 没有显示,我将此消息发送到控制台:
警告:尝试呈现不在窗口层次结构中的 View !
如何在不使用 Storyboard的情况下在两个 View 之间导航?
最佳答案
1) 将 mainNavigationController 设置为 rootViewController
2) 使用 self.navigationController?.pushViewController(secondViewController, animated: true)
解释
逻辑上,当您将 TineLineViewController 设置为应用程序的委托(delegate) rootViewController 属性时,您的 Root View Controller 是 UINavigationController。这就是为什么你会异常(exception)。
self.mainNavigationController = UINavigationController()
var mainController: UIViewController? = TineLineViewController()
self.mainNavigationController!.pushViewController(mainController!, animated: true)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// ERROR is here
// self.window!.rootViewController = mainController
// your root view controller should be navigation controller
self.window!.rootViewController = mainNavigationController
self.window!.makeKeyAndVisible()
关于ios - 在两个 viewController 之间导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30566586/