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

问题描述

此代码在UIViewController中正常工作:

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

但是现在我想在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")
        }
    }
}

在SwiftUI视图中启动新视图的最佳方法是什么?

上面的代码抛出错误:

“ AppRootView”类型的值没有成员“ navigationController”

解决方法

您可以使用NavigationLink来显示视图。

在后台添加一个空的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")
        }
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...