在两个viewController

时间:2015-06-01 06:02:51

标签: ios swift uiviewcontroller appdelegate

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

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会显示出来,而没有动画......

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

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

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

*由于未捕获的异常'UIViewControllerHierarchyInconsistency'而终止应用程序,原因是:'将根视图控制器添加为视图控制器的子级:' * 第一次抛出调用堆栈: (

我不知道这是否是在rootviewController中设置appDelagate课程的最佳方法,为什么在不将此行添加到我的potLeft函数的情况下无法导航:

appDelegate.window?.rootViewController = secondViewController

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

警告:尝试在窗口层次结构中显示其视图!

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

2 个答案:

答案 0 :(得分:2)

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

<强>解释

逻辑上,在将TineLineViewController设置为app的委托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()

答案 1 :(得分:0)

您可以使用动画将secondViewController设置为rootViewController navigationController

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

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

希望这对你有帮助!