gpt4 book ai didi

没有场景委托(delegate)的 SwiftUI 2 弹出到 Root View

转载 作者:行者123 更新时间:2023-12-04 02:28:22 25 4
gpt4 key购买 nike

我想在用户注销时刷新 Root View ,但在新的无场景 SwiftUi 2 下我找不到如何做到这一点。
接下来是@Swissmark发布的解决方案我试图在 SwiftUI 2 中实现:

let contentView = AppRootView(showingView: ShowingView(showingView: appStartView))

if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}

最佳答案

一个可能的解决方案是创建一个 ObservableObject负责路由:

enum AppView {
case login, main
}

class ViewRouter: ObservableObject {
// here you can decide which view to show at launch
@Published var currentView: AppView = .login
}
然后,你可以注入(inject)这个 ViewRouter作为 EnvironmentObject到 Root View :
@main
struct TestApp: App {
@StateObject private var viewRouter = ViewRouter()

var body: some Scene {
WindowGroup {
RootView()
.environmentObject(viewRouter)
}
}
}
现在您可以从任何 View 更改当前 View :
struct RootView: View {
@EnvironmentObject private var viewRouter: ViewRouter

var body: some View {
VStack {
if viewRouter.currentView == .login {
LoginView()
} else if viewRouter.currentView == .main {
MainView()
}
}
}
}

struct LoginView: View {
@EnvironmentObject private var viewRouter: ViewRouter

var body: some View {
VStack {
Text("Login View")
Button("Log in") {
viewRouter.currentView = .main
}
}
}
}

struct MainView: View {
@EnvironmentObject private var viewRouter: ViewRouter

var body: some View {
VStack {
Text("Main View")
Button("Log out") {
viewRouter.currentView = .login
}
}
}
}

关于没有场景委托(delegate)的 SwiftUI 2 弹出到 Root View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65800522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com