我一直在做一个 Swift 项目,我有两个 View Controller ,登录 View Controller 和主页 View Controller 。当用户启动应用程序时,如果用户未登录,我想显示登录 View Controller ,另一方面,如果用户已登录,我想显示主视图 Controller 。
所以流程会是这样的。
当用户未登录时,显示
- 登录 View Controller
- 主视图 Controller
当用户已经登录时,显示
- 主视图 Controller
在场景委托(delegate)中,我写了
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: scene.coordinateSpace.bounds)
window?.windowScene = scene
window?.rootViewController = HomeViewController() or LoginViewController() depending on the user's login status
window?.makeKeyAndVisible()
}
我想知道我是否应该将 HomeViewController 应用为 rootviewcontroller 而不管用户的登录状态(并且当用户未登录时可能在 homeVC 上显示 loginVC),或者我应该根据用户的登录切换 View Controller 状态。
那么,在这种情况下,切换rootviewcontroller有什么意义呢?为什么要(或不重要)切换 Root View Controller ?
当我将 View Controller 应用到 Root View Controller 属性时,有什么我应该考虑的吗?
最佳答案
// SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
// if user is logged in before
if let loggedUsername = UserDefaults.standard.string(forKey: "username") {
window?.rootViewController = HomeViewController()
} else {
// if user isn't logged in
window?.rootViewController = LoginViewController()
}
}
关于ios - 什么时候需要切换 rootViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70888593/