如何在不使用NavigationLink的情况下使用SwiftUI推送新的根视图? [英] How to push a new root view using SwiftUI without NavigationLink?
问题描述
我有一个登录屏幕.用户填满凭据后,我想对其进行验证,然后启动一个新的根视图,这样用户将无法导航回到登录视图. 我目前有
I have a login screen. After user fill up credential, I want to verify it then start a new root view so user won't be able to navigate back to the login view. I currently have
Button(action: {
// launch new root view here
}, label: {Text("Login")}).padding()
我在网上找到的大多数答案都使用了我不想使用的导航链接.其他一些答案建议使用UIApplication.shared.delegate
的AppDelegate
,这对我不起作用,因为我有SceneDelegate
Majority of answers I found online are using navigation link which I don't want to. Some other answers suggest to utilize AppDelegate
by UIApplication.shared.delegate
which isn't working for me because I have SceneDelegate
推荐答案
下面是使用通知完全替换根视图的另一种可能方法
Here is possible alternate approach of how to replace root view completely... using notifications
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)
})
在您想要的地方发布所需的通知
in your desired place post needed notification
Button(action: {
// launch new root view here
NotificationCenter.default.post(loginRootViewNotification)
}, label: {Text("Login")}).padding()
这篇关于如何在不使用NavigationLink的情况下使用SwiftUI推送新的根视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!