对于一个新的SwiftUI iOS应用程序,我在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()
}
当用户尚未注册或登录时,他们将被带到注册流程。
用户注册后,如何将RootView切换到TabView?我似乎找不到使用SwiftUI的任何解决方案。
我应该改为使用Environment对象并侦听如何更改用户的Auth Status?
声明一个AppRootView,类似这样:
struct AppRootView: View {
@ObservedObject private var auth: Auth
var body: some View {
Group {
if auth.token != nil {
MainTabbedView()
} else {
StartRegistrationView()
}
}
}
}
然后在SceneDelegate中将其设置为根视图:
window.rootViewController = UIHostingController(rootView: AppRootView(auth: $auth))
您必须像上面一样传递视图或在您的环境中进行设置,以将视图绑定到Auth()。 SwiftUI的优点在于,只要令牌不为零,视图就会重新绘制,并且您的用户会在MainTabbedView中找到它们。