问题
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