SwiftUI.
I’ve a View that comprises a NavigationStack, which takes an argument “path” of kind: Binding
.
(I’m planning to make use of this View as a navigation container.)
I need to cross the “path” worth instantly or no less than in some summary approach — with out specifying the precise ObservableObject
class that owns the precise @Printed
variable.
I managed to cross the worth by specifying the proudly owning class, however this can be a inflexible answer. I need to make it extra versatile.
A working however inflexible answer:
struct ContainerView: View {
@ObservedObject var router: Router
let initialView: InitialView
var physique: some View {
NavigationStack(path: $router.path) {
self.initialView
.navigationDestination(for: NavigationDestination.self) { vacation spot in
swap vacation spot {
case .mainScreen:
Textual content("Error")
.onAppear() {
assertionFailure()
}
case .particulars(let detailsView):
detailsView
}
}
}
}
}
What I Tried:
I believed I may manually create a computed property of kind Binding
from @Printed
variable of kind [NavigationDestination]
within the Router
class like this:
var pathBinding: Binding<[NavigationDestination]> {
let binding = Binding(
get: { self.path },
set: { self.path = $0 }
)
return binding
}
…and cross it into my ContainerView
, in order that it seems to be like this:
struct ContainerView: View {
var path: Binding<[NavigationDestination]>
let initialView: InitialView
var physique: some View {
NavigationStack(path: path) {
self.initialView
.navigationDestination(for: NavigationDestination.self) { vacation spot in
swap vacation spot {
case .mainDiscoveryScreen:
Textual content("Error")
.onAppear() {
assertionFailure()
}
case .particulars(let detailsView):
detailsView
.onAppear() {
print("Particulars proven")
}
}
}
}
}
}
Creating the View:
let discoveryContainerView = DiscoveryContainerView(path: pathBinding, initialView: suggestionsView)
This code compiled however didn’t work. When the unique path variable modified, nothing occurred.
I additionally tried utilizing a protocol, however property wrappers can’t be utilized in protocols. This implies I couldn’t create a protocol with a @Printed
property.
Remaining Query:
How can I flexibly cross a variable into ContainerView
, the place it’s anticipated as Binding
, from an ObservableObject
class that owns it as @Printed var path: [NavigationDestination]
, with out passing a reference to the category occasion itself?