无法以编程方式切换回以前的根View Controller

时间:2014-11-23 00:31:34

标签: ios xcode swift xcode6 uistoryboard

我在故事板上有两个视图控制器,我想在某些条件下切换它们(例如,按下按钮),所以我写了下面的代码:

// FirstViewController.swift
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
if let keyWindow = UIApplication.sharedApplication().keyWindow {
    keyWindow.rootViewController = rootViewController
}

// SecondViewController.swift
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as FirstViewController
if let keyWindow = UIApplication.sharedApplication().keyWindow {
    keyWindow.rootViewController = rootViewController
}

从第一个视图控制器切换到第二个工作按预期工作,但是当我尝试切换回第一个视图控制器时,它会改变片刻,但会再次自动显示第二个视图控制器。奇怪的是,如果我将“切换”代码更改为以下

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.presentViewController(rootViewController, animated: true, completion: nil)

它按预期工作。

为什么呢?我究竟做错了什么?我该如何解决?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以通过创建基本导航控制器并将其用作切换器来代替更改窗口的rootViewController:

class BaseViewController: UINavigationController {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder);

        // You can skip this step if you instantiate BaseViewController in a
        // storyboard and set its root segue to FirstViewController
        self.viewControllers = [FirstViewController(nibName:"FirstViewController", bundle:nil)]
    }

    override func pushViewController(viewController: UIViewController, animated: Bool) {
        self.viewControllers = [viewController]
    }
}


class FirstViewController: UIViewController {

    required init(coder aDecoder: NSCoder) {
        super.init(nibName: "FirstViewController", bundle: nil)
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    @IBAction func goToSecond(sender: AnyObject) {
        self.navigationController?.pushViewController(SecondViewController(nibName:"SecondViewController", bundle:nil), animated: true);   
    }
}


class SecondViewController: UIViewController {

    required init(coder aDecoder: NSCoder) {
        super.init(nibName: "SecondViewController", bundle: nil)        
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    @IBAction func goToFirst(sender: AnyObject) {
        self.navigationController?.pushViewController(FirstViewController(nibName:"FirstViewController", bundle:nil), animated: true);    
    }
}

在这里,我正在从nib加载视图控制器。但是,您可以像在示例中一样轻松地从故事板中实例化它们。此外,您可以隐藏导航栏,使其看起来不像导航上下文。