ios - 什么时候需要切换 rootViewController

标签 ios swift xcode rootviewcontroller uiscenedelegate

我一直在做一个 Swift 项目,我有两个 View Controller ,登录 View Controller 和主页 View Controller 。当用户启动应用程序时,如果用户未登录,我想显示登录 View Controller ,另一方面,如果用户已登录,我想显示主视图 Controller 。

所以流程会是这样的。

当用户未登录时,显示

  1. 登录 View Controller
  2. 主视图 Controller

当用户已经登录时,显示

  1. 主视图 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/

相关文章:

ios - UITableViewCell 样式和 dequeueReusableCellWithIdentifier

ios - AVPlayer 需要很长时间才能开始播放

ios - "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"- swift

ios - Swift 中的泛型选择器 View

ios - 具有 UILabel 行为的自动布局无法解释

ios - 如何在协议(protocol)中设置读写内部、只读外部属性

ios - TestFlight 当前不可用消息

swift - WKInterfaceTable 未填充可编码数据

iphone - 如何通过 Xcode 在我的设备上运行发布配置

ios - 点击单元格时 Xcode UI 测试 XCTDaemonErrorDomain Code=13