具有不同目的地的 SwiftUI 导航栏项目

SwiftUI Navigation Bar Item with different destinations

我有一个带有添加按钮 (NavigationBarItem) 的导航视图,我想在每个选项卡中设置不同的导航栏项目目的地。

enum Tab: String {
    case income = "Income"
    case expenses = "Expenses"
    case budgets = "Budget"
    case investment = "Investment"
    case assets = "Asset"  
}

我已经尝试将视图作为原始值提供给结构,但这是不可能的。我该怎么做?

var body: some View {
    NavigationView {
        TabView(selection: $selection) {
            Text("Place Holder Income")
                .tabItem {
                    Label("Income", systemImage: "star")
                }
                .tag(Tab.income)
                .navigationBarHidden(false)
            
            ExpensesView()
                .tabItem {
                    Label("Expenses", systemImage: "star")
                }
                .tag(Tab.expenses)
                .navigationBarHidden(false)
            
            Text("Place Holder Budgets")
                .tabItem {
                    Label("Budgets", systemImage: "star")
                }
                .tag(Tab.budgets)
                .navigationBarHidden(false)
            
            Text("Place Holder Investment")
                .tabItem {
                    Label("Investment", systemImage: "star")
                }
                .tag(Tab.investment)
                .navigationBarHidden(false)
            
            Text("Place Holder Assets")
                .tabItem {
                    Label("Assets", systemImage: "star")
                }
                .tag(Tab.assets)
                .navigationBarHidden(false)
    }
        .navigationTitle(selection.rawValue)
        .navigationBarItems(
            trailing:
                NavigationLink("Add", destination: AddExpensesView())
        )
    
    }
}

您可以添加一个函数(在您看来)路由到正确的目的地(取决于“选择”的值 属性)。

@ViewBuilder func addView() -> some View {
        switch selection {
        case .income: Text("Income destination")
        case .expenses: Text("Expenses destination")
        default: Rectangle()
        }
    }

您的 NavigationLink 调用此视图构建器:

NavigationLink("Add", destination: addView())