Change the root view of UIHostingController in SwiftUI

前端 未结 5 927
情歌与酒
情歌与酒 2020-12-03 07:19

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

if let windowScene = scene as? UIWindowScene {
    let window =          


        
5条回答
  •  悲哀的现实
    2020-12-03 08:11

    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()
                }
            }
        }
    }
    

    and then in SceneDelegate set it as the root view:

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

    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.

提交回复
热议问题