In my navigation, I want to be able to go from ContentView
-> ModelListView
-> ModelEditView
OR ModelAddView
.
Currently placing a NavigationLink
in the .navigationBarItems
may cause some issues.
A possible solution is to move the NavigationLink
to the view body and only toggle a variable in the navigation bar button:
struct ModelListView: View {
@State var modelViewModel = ModelViewModel()
@State var isAddLinkActive = false // add a `@State` variable
var body: some View {
List(modelViewModel.modelValues.indices) { index in
NavigationLink(
destination: ModelEditView(model: $modelViewModel.modelValues[index]),
label: {
Text(modelViewModel.modelValues[index].titel)
}
)
}
.background( // move the `NavigationLink` to the `body`
NavigationLink(destination: ModelAddView(modelViewModel: $modelViewModel), isActive: $isAddLinkActive) {
EmptyView()
}
.hidden()
)
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing: trailingButton)
}
// use a Button to activate the `NavigationLink`
var trailingButton: some View {
Button(action: {
self.isAddLinkActive = true
}) {
Image(systemName: "plus")
}
}
}