I've got a NavigationStack and I'm passing bindings to multiple children through a couple of different views. If I don't pass the children as bindings then everything works as intended. Also if I uncomment the @Environment aspect, everything works as intended. Not sure if this is a bug or an artefact of SwiftUI that I've missed?
Here is a simplified version of what I have:
struct Parent: Identifiable, Equatable {
static func == (lhs: Parent, rhs: Parent) -> Bool {
return lhs.id == rhs.id
}
let id = UUID()
var name: String = ""
var children: [Child] = [.init()]
}
struct Child: Identifiable, Equatable {
static func == (lhs: Child, rhs: Child) -> Bool {
return lhs.id == rhs.id
}
let id = UUID()
var name = "Child"
}
struct ContentView: View {
var body: some View {
MainView()
}
}
struct MainView: View {
@State var parents: [Parent] = [.init(name: "Parent 1"), .init(name: "Parent 2")]
var body: some View {
NavigationStack {
ForEach($parents) { parent in
NavigationLink {
DetailParent(parent: parent)
} label: {
Text(parent.wrappedValue.name)
}
}
}
}
}
struct DetailParent: View {
@Binding var parent: Parent
@Environment(\.dismiss) var dismiss // MARK: Commenting this out makes this work
var body: some View {
ForEach($parent.children) { child in
NavigationLink {
DetailChild(child: child)
} label: {
Text(child.wrappedValue.name)
}
}
}
}
struct DetailChild: View {
@Binding var child: Child
var body: some View {
Text(child.name)
}
}
I need to pass @Binding to both DetailParent and DetailChild as I need to mutate both the Parent object, and Child object. The dismiss comes into play when I delete the Parent from DetailParent view. i.e. I would like to delete a Parent object from the parents variable (using a callback function, which works as intended), and then dismiss (pop back up to the MainView) the DetailParent view as the content has been deleted.
I've tried changing how the NavigationStack works (i.e. using NavigationDestination) to no avail.