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

查看:1511
本文介绍了在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天全站免登陆