Changing rootViewController doesn't display viewController set as root

可紊 提交于 2021-02-11 15:05:40

问题


I have an initialViewController, if I find user login information, I route user to Home, but if I don't, I set register/login ViewController as root. I tested with break points that my register/login ViewController didLoad and didAppear getting execute, but my register/login ViewController don't show and initialViewController remains on screen. this is my code:

public static func setRootViewController(withId id: String, storyBoardName: String) {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: storyBoardName, bundle: nil)
    let newRootVC = mainStoryboard.instantiateViewController(withIdentifier: id)
    appDelegateRef.window!.rootViewController = newRootVC
}

and this is part of my storyboard:

what's the problem here?


回答1:


Put this function in your AppDelegate class. You can call this function from anywhere in your view controllers.

class AppDelegate: UIResponder, UIApplicationDelegate {
    // ...

    public func present(viewController: UIViewController) {
        guard let window = window else { return }
        UIView.transition(with: window, duration: 0.5, options: .transitionFlipFromLeft, animations: {
            window.rootViewController = viewController
        }, completion: nil)
    }
}

In the view controller you want the user to log out from, call the function above this way:

public static func setRootViewController(withId id: String, storyBoardName: String) {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: storyBoardName, bundle: nil)
    let newRootVC = mainStoryboard.instantiateViewController(withIdentifier: id)

    guard let delegate = UIApplication.shared.delegate as? AppDelegate else { return }
    delegate.present(viewController: newRootVC)
}



回答2:


use appDelegateRef.window!.makeKeyAndVisible() at end of your function

public static func setRootViewController(withId id: String, storyBoardName: String) {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: storyBoardName, bundle: nil)
    let newRootVC = mainStoryboard.instantiateViewController(withIdentifier: id)
    appDelegateRef.window!.rootViewController = newRootVC
    appDelegateRef.window!.makeKeyAndVisible()
}


来源:https://stackoverflow.com/questions/53920649/changing-rootviewcontroller-doesnt-display-viewcontroller-set-as-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!