Swift instantiateViewControllerWithIdentifier

时间:2014-09-18 13:58:29

标签: ios swift

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

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

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

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

1 个答案:

答案 0 :(得分:6)

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

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

通过这种方式,您将观察属性授权,每次更改时,都会调用正确的方法。