ios - 如何在没有 NavigationLink 的情况下使用 SwiftUI 推送新的 Root View ?

标签 ios swiftui

我有一个登录屏幕。用户填写凭据后,我想验证它然后启动一个新的根 View ,这样用户将无法导航回登录 View 。
我目前有

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

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

最佳答案

这是如何完全替换根 View 的可能替代方法......使用通知

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

关于ios - 如何在没有 NavigationLink 的情况下使用 SwiftUI 推送新的 Root View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60134061/

相关文章:

ios - 在 Restkit 中映射 JSON 很困难

iphone - 使用位于另一个导航 Controller 内的导航 Controller 查看错误

file - 如何从基于 SwiftUI 文档的应用程序将多个文件保存在包文件夹中?

ios - 是否可以迁移旧的 Xcode 项目以使用 SwiftUI?

ios - GeometryReader 在 SwiftUI 中占用额外空间

ios - 将 Gamesparks 与 iOS 集成的问题

iphone - 运行以下代码时 iOS 应用程序崩溃

iOS 声音无法在 Swift 中播放

ios - 如何知道用户点击了 TextView 的哪一行

swiftui - 在 macOS 上的 SwiftUI 中将颜色从源拖放到目标