Swift instantiateViewControllerWithIdentifier

目前我有:1。初始ViewController – AppStateViewController 2 .TabBarController – AuthorizedSessionViewController 3. ViewController – UnauthorizedSessionViewController

AppStateViewController代码 – https://gist.github.com/nspavlo/de7a03f80e57694a12ba

如果我在viewDidLoad()中调用switchToAuthorizedSessionViewController()和switchToUnauthorizedSessionViewController(),则会出现AuthorizedSessionViewController而不是UnauthorizedSessionViewController。

我的gol是在didFinishLaunchingWithOptions上加载右控制器,并在更改appState时更改它。

为什么在switchToViewController()方法中使用switchToAuthorizedSessionViewController():

func switchToViewController(identifier: String) { let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as UIViewController self.navigationController?.setViewControllers([viewController], animated: false) **switchToAuthorizedSessionViewController()** } 

你将用它创建一个无限循环,试试这个:

 class AppStateViewController: UIViewController { var authorized: Bool = false { didSet { if authorized { switchToAuthorizedSessionViewController() } else { switchToUnauthorizedSessionViewController() } } } override func viewDidLoad() { super.viewDidLoad() self.authorized = false } func switchToAuthorizedSessionViewController() { let sessionViewControllerID = "AuthorizedSessionViewController" switchToViewController(sessionViewControllerID) } func switchToUnauthorizedSessionViewController() { let sessionViewControllerID = "UnauthorizedSessionViewController" switchToViewController(sessionViewControllerID) } func switchToViewController(identifier: String) { let viewController =self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as UIViewController self.navigationController?.setViewControllers([viewController], animated: false) } } 

有了这个,您将观察授权的财产,每次更改它,它将调用正确的方法。