如何在不使用NavigationLink的情况下使用SwiftUI推送新的根视图?

问题描述 投票:0回答:1

我有一个登录屏幕。用户填满凭据后,我想对其进行验证,然后启动新的根视图,这样用户将无法导航回登录视图。我目前有

Button(action: { 
// launch new root view here 
}, label: {Text("Login")}).padding()

我在网上找到的大多数答案都使用了我不想使用的导航链接。其他一些答案建议利用AppDelegate来利用UIApplication.shared.delegate,这对我不起作用,因为我有SceneDelegate

ios swiftui
1个回答
0
投票

这里是可能的替代方法,该方法如何完全替换根视图...使用通知

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    let loginRootViewNotification = 
         NSNotification.Name("loginRootViewNotification") // declare notification
    private var observer: Any?               // ... and observer


    ...
    // in place of window creation ...
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)

        observer = NotificationCenter.default.addObserver(forName: loginRootViewNotification, object: nil, queue: nil, using: { _ in
            let anotherRootView = AnotherRootView() 
            // create another view on notification and replace
            window.rootViewController = UIHostingController(rootView: anotherRootView)
        })

在您想要的地方发布需要的通知

Button(action: { 
// launch new root view here 
   NotificationCenter.default.post(loginRootViewNotification)
}, label: {Text("Login")}).padding()
© www.soinside.com 2019 - 2024. All rights reserved.