简体   繁体   English

如何在 SwiftUI 视图中进行导航控制

[英]How to do navigation control in SwiftUI view

This code works fine inside UIViewController :此代码在UIViewController内工作正常:

let hostingController = UIHostingController(rootView: homeMainView())
self.navigationController?.pushViewController(hostingController, animated: true)

but now I want to use it in SwiftUI View this way:但现在我想在 SwiftUI 中使用它 以这种方式查看:

struct AppRootView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("App").bold()
                .font(.largeTitle)
        }.onAppear(perform: handleSignIn)
            .frame(minWidth: 0,
                   maxWidth: .infinity,
                   minHeight: 0,
                   maxHeight: .infinity).background(Color.yellow)
    }

    func handleSignIn() {
        if let _ = app.currentUser() {
            print("user is logged in")

            let hostingController = UIHostingController(rootView: homeMainView())
            self.navigationController?.pushViewController(hostingController, animated: true)

        } else {
            print("not logged in; present sign in/signup view")
        }
    }
}

What is the best way to launch the new view in SwiftUI view?在 SwiftUI 视图中启动新视图的最佳方式是什么?

The above code throws an error:上面的代码抛出一个错误:

Value of type 'AppRootView' has no member 'navigationController' “AppRootView”类型的值没有成员“navigationController”

You may present your view using a NavigationLink .您可以使用NavigationLink呈现您的视图。

Add an empty NavigationLink in the background and set isLinkActive if the user is logged in. You need to wrap it all in the NavigationView as well:在后台添加一个空的NavigationLink并设置isLinkActive如果用户已登录。您还需要将其全部包装在NavigationView中:

struct AppRootView: View {
    @State var isLinkActive = false // <- add here

    var body: some View {
        NavigationView { // <- wrap in the `NavigationView`
            VStack(alignment: .leading) {
                Text("App")
                    .bold()
                    .font(.largeTitle)
            }
            .navigationBarTitle("", displayMode: .inline) // optionally set title
            .navigationBarHidden(true)
            .background( // add a hidden `NavigationLink` in the background
                NavigationLink(destination: homeMainView(), isActive: $isLinkActive) {
                    EmptyView()
                }
                .hidden()
            )
        }
        .onAppear(perform: handleSignIn)
        .frame(minWidth: 0,
               maxWidth: .infinity,
               minHeight: 0,
               maxHeight: .infinity).background(Color.yellow)
    }

    func handleSignIn() {
        if let _ = app.currentUser() {
            isLinkActive = true // <- activate the `NavigationLink`
        } else {
            print("not logged in; present sign in/signup view")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM