Swiftui - How to Avoid Navigation Hardcoded into the View

How to navigate to a View in SwiftUI without NavigationLink

First of all - congratulations: This is the first such complex code, that flawlessly runs on copy/paste into Xcode ... doesn't happen often :)

To your question:

You almost have it. The only thing is that your productFamilyIsActive is a Bool – that can only hold info on ONE selected NavigationLink, you have 3. But it can if you change it to an optional selection:

class Navigation: ObservableObject {
@Published var productFamilyIsActive : String? = nil // here
}

For that you use a different init on NavigationLink here:

struct ProductFamilyRow: View {

@EnvironmentObject var navigation : Navigation
@State var productFamily : String

var body: some View {
NavigationLink(destination: PartNumberView(productFamily: productFamily),
tag: productFamily, // here
selection: $navigation.productFamilyIsActive) { // and here
Text("\(productFamily)")
}
.isDetailLink(false)
}
}

Lastly you don't set to false but to nil here:

struct HomeButtonView: View {

@EnvironmentObject var navigation : Navigation

var body: some View {
Button(action: {
self.navigation.productFamilyIsActive = nil // here
}, label: {
Image(systemName: "house")
})
.environmentObject(navigation)
}
}

Voila!

Navigation View moved my destination view SwiftUI

In some cases, you have to make view's frame not hardcore that solve this problem but in my case problem is I added navigation view two times so I had this issue.

I removed navigation view in secondary view and that solved my issue completely.

NavigationLink .navigationDestination called multiple times and pushes to new View twice

The problem seems to be resolved in iOS 16 beta 5.



Related Topics



Leave a reply



Submit