1

I have a Navigation View with an Add button(NavigationBarItem) and want to set a different destination of the Navigation Bar item in each tab.

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

I have already tried to give the struct the view as raw value but this is not possible. How can I do this?

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())
        )
    
    }
}
ShadowHawwk
  • 29
  • 1
  • 3
  • I think you could have the add button open an "AddView" and pass the selected tab binding to that view. That view would act as a router view and present the appropriate add view (eg `AddExpensesview`) – Paulw11 Aug 15 '21 at 22:43

1 Answers1

0

You could add a function (in your view) that routes to the right destination (depending on the value of the "selection" property).

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

Your NavigationLink calls this view builder :

NavigationLink("Add", destination: addView())
Adrien
  • 1,579
  • 6
  • 25