在两个 viewController 之间导航

Navigating between two viewController

我在 appDelegate 中将我的初始 ViewController 设置为 rootViewController 因为我不使用故事板。看起来像这样:

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 出现了。

我在这个 class 中有一个调用此方法的 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 就会出现,但没有动画...

如果我尝试以这种方式更改视图:

self.navigationController?.pushViewController(secondViewController, animated: true)

它仍然没有任何动画,在 secoundViewController 出现后我的应用程序崩溃并显示此消息:

* 由于未捕获的异常 'UIViewControllerHierarchyInconsistency' 而终止应用程序,原因:'adding a root view controller as a child of view controller:' * 首先抛出调用栈: (

我不知道这是否是在 appDelagate 中设置我的 rootviewController class 的最佳方式,以及为什么不将此行添加到我的 potLeft 函数就无法导航:

appDelegate.window?.rootViewController = secondViewController

如果没有这一行,我可以在我的应用程序控制台中看到,调用了 secondViewController viewDidLoad 方法,但控制器没有显示,我将此消息发送到控制台:

警告:试图展示其视图不在 window 层次结构中!

如何在不使用故事板的情况下在两个视图之间导航?

您可以将 secondViewController 设置为带有动画的 navigationControllerrootViewController

func postLeft(_sender: AnyObject?)
{
    println("go to secound view..")
    let secondViewController = PostCreateController()

    self.navigationController?.setViewControllers([secondViewController], animated: true)
}

希望对您有所帮助!

1) 将 mainNavigationController 设置为 rootViewController 2) 使用 self.navigationController?.pushViewController(secondViewController, animated: true)

说明

逻辑上,当您将 TineLineViewController 设置为应用程序的委托 rootViewController 属性 时,您的根视图控制器是 UINavigationController。这就是为什么你会例外。

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()