gpt4 book ai didi

ios - SwiftUI:如何以编程方式更改 rootview Controller

转载 作者:行者123 更新时间:2023-12-01 21:26:16 24 4
gpt4 key购买 nike

我试图在用户注销后将 rootview Controller 更改为不同的屏幕。

    if let window = UIApplication.shared.windows.first {
window.rootViewController = UIHostingController(rootView: SignInView())
window.endEditing(true)

window.makeKeyAndVisible()
}
这就是我到目前为止所拥有的。它导航到不同的 View ,但它使新 View 上的按钮无法使用。有没有更好的方法来改变 rootview 或者我错过了什么?

最佳答案

我的方法是创建一个可观察的对象来协调各种应用程序 View 之间的导航。下面一个简化的例子给你一个想法:

//Your app views
enum AppViews {
case LoginView
case MainAppView
}

//Class that conforms to the ObservableObject protocol and publishes the viewId property.
//Basically your navigation will react to viewId changes

class ShowingView: ObservableObject {

init(showingView: AppViews) {
self.viewId = showingView
}

@Published var viewId : AppViews
}

//The current root view of your app is observing changes of the ShowingView class and switch between your app views
struct AppRootView: View {

@ObservedObject var showingView: ShowingView

var body: some View {
Group {
if showingView.viewId == .LoginView {
TermsAndConditionsView()
.environmentObject(showingView)
}
else {
MainAppView()
.environmentObject(showingView)
}
}
}
}
请注意,您可以通过 showingView作为 environmentObject 到您的 View ,并在需要时使用它切换到另一个 View 。在您的情况下,当用户注销时切换到另一个屏幕。
在您的 现场委托(delegate)然后,您可以例如在登录和主视图之间切换,如下所示
var appStartView: AppViews

let isloggedIn = UserDefaults.standard.bool(forKey: "IsLoggedIn")

if isLoggedIn == false {
appStartView = .LoginView
}
else {
appStartView = .MainAppView
}

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()
}
MainAppView 之间切换和 LoginView您可以简单地修改 environmentObject showingView 的值
self.showingView.viewId = AppViews.LoginView
我希望它有助于指导您朝着正确的方向前进

关于ios - SwiftUI:如何以编程方式更改 rootview Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63461933/

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