It seems to me that Apple is encouraging us to give up using UIViewController in SwiftUI, but without using view controlelrs, I feel a little bit powerless. Wha
I'm adding some snippets here because I think it simplifies some things and makes reusing navigation links easier:
1. Add View Navigation Extensions
extension View {
func navigatePush(whenTrue toggle: Binding) -> some View {
NavigationLink(
destination: self,
isActive: toggle
) { EmptyView() }
}
func navigatePush(when binding: Binding,
matches: H) -> some View {
NavigationLink(
destination: self,
tag: matches,
selection: Binding(binding)
) { EmptyView() }
}
func navigatePush(when binding: Binding,
matches: H) -> some View {
NavigationLink(
destination: self,
tag: matches,
selection: binding
) { EmptyView() }
}
}
Now, you can call on any view (make sure they (or a parent) are in a navigation view)
2. Use at leisure
struct Example: View {
@State var toggle = false
@State var tag = 0
var body: some View {
NavigationView {
VStack(alignment: .center, spacing: 24) {
Text("toggle pushed me")
.navigatePush(whenTrue: $toggle)
Text("tag pushed me (2)")
.navigatePush(when: $tag, matches: 2)
Text("tag pushed me (4)")
.navigatePush(when: $tag, matches: 4)
Button("toggle") {
self.toggle = true
}
Button("set tag 2") {
self.tag = 2
}
Button("set tag 4") {
self.tag = 4
}
}
}
}
}