I'm experiencing a weird issue where a navigation link will break when I don't want it to. I'm using a state based navigation system that looks like this :
@State var isNavActive: Bool = false
@State var destination: AnyView = AnyView(EmptyView())
func getDestination() -> AnyView {
return destination
}
func navigationLink() -> some View {
NavigationLink(destination: getDestination(), isActive: $isNavActive) {
EmptyView()
}
}
func navigate<Destination: View>(destination: Destination) {
self.destination = AnyView(destination)
isNavActive = true
}
I have a singleton class that manages some general app state that one screen observes. There is a view on that page that displays a published variable in the singleton. When you click on that view, you navigate to separate view where that variable can be changed.
Whenever the variable is changed on this view, the navigation link breaks and it automatically navigates back to the first screen. I don't want this to happen.
Here is what the code looks like :
class SingletonClass : ObservableObject {
static let shared = SingletonClass()
private init() {}
@Published var publishedVariable : VariableClass
func setPublishedVariable(value : VariableClass) -> { self.publishedVariable = value }
}
class VariableClass {...properties}
struct Screen1 : View {
*** All of the navigation code above ***
@ObservedObject var vm = SingletonClass.shared
var body : some View {
VStack {
navigationLink()
Button {
navigate(destination : Screen2())
} {
SomeDisplay(value : vm.publishedVariable)
}
} }
}
struct Screen2 : View {
@ObservedObject var vm = SingletonClass.shared
var body : some View {
ForEach(someArrayOfVariableClass) { varClass in
SomeDisplay(val : varClass)
.onTapGesture {
vm.setPublishedVariable(val : varClass)
}
^^ the issue occurs here. As soon as any one of these Views is pressed, the app automatically redirects back to Screen1
}
}
Does anybody know why this is happening or how I can fix it? Thank you