在 SwiftUI 中更改 UIHostingController 的根视图 [英] Change the root view of UIHostingController in SwiftUI

查看:25
本文介绍了在 SwiftUI 中更改 UIHostingController 的根视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于新的 SwiftUI iOS 应用程序,我在 SceneDelegate

For a new SwiftUI iOS app, I do the following in the SceneDelegate

if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    if Auth().token == nil {
        window.rootViewController = UIHostingController(rootView: StartRegistrationView())
    } else {
        window.rootViewController = UIHostingController(rootView: MainTabbedView())
    }
    self.window = window
    window.makeKeyAndVisible()
}

当用户尚未注册或登录时,他们将进入注册流程.

When a user hasn't signed up or logged in they are taken to the registration flow.

一旦用户注册,我如何将 RootView 切换到我的 TabView?我似乎无法使用 SwiftUI 找到任何解决方案.

Once a user has signed up, how can I switch the RootView to go to my TabView? I can't seem to find any solution using SwiftUI.

我应该改用 Environment 对象并监听用户 Auth 状态的变化吗?

Should I instead use an Environment object and listen for changes to the User's Auth Status?

推荐答案

声明一个 AppRootView,像这样:

Declare an AppRootView, something like this:

struct AppRootView: View {

    @ObservedObject private var auth: Auth
    var body: some View {
        Group {
            if auth.token != nil {
                MainTabbedView()
            } else {
                StartRegistrationView()
            }
        }
    }
}

然后在 SceneDelegate 中将其设置为根视图:

and then in SceneDelegate set it as the root view:

window.rootViewController = UIHostingController(rootView: AppRootView(auth: $auth))

您必须将您的视图绑定到您的 Auth() ,方法是像我上面所做的那样传入它或在您的环境中设置它.SwiftUI 的美妙之处在于,只要令牌不为零,视图就会重绘,您的用户将在 MainTabbedView 中找到它们自己.

You have to bind your view to your Auth() either by passing it in as I did above or by setting it on your environment. The beauty of SwiftUI is that as soon as the token is not nil, the view will redraw and your user will find them selves in MainTabbedView.

这篇关于在 SwiftUI 中更改 UIHostingController 的根视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆