What's equivalent to the Push and Pop of a view controller in SwiftUI?
1 Answer
Root :
window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(Model()))
iOS version 13.1 :
class Model: ObservableObject {
@Published var pushed = false
}
struct ContentView: View {
@EnvironmentObject var model: Model
var body: some View {
NavigationView {
VStack {
Button("Push") {
self.model.pushed = true
}
NavigationLink(destination: DetailView(), isActive: $model.pushed) { EmptyView() }
}
}
}
}
struct DetailView: View {
@EnvironmentObject var model: Model
var body: some View {
Button("Bring me Back") {
self.model.pushed = false
}
}
}
Removing the default back button and adding our own will let us get through, until the bug gets fixed by Apple.
class Model: ObservableObject {
@Published var pushed = false
}
struct ContentView: View {
@EnvironmentObject var model: Model
var body: some View {
NavigationView {
VStack {
Button("Push") {
self.model.pushed = true
}
NavigationLink(destination: DetailView(), isActive: $model.pushed) { EmptyView() }
}
}
}
}
struct DetailView: View {
@EnvironmentObject var model: Model
var body: some View {
Button("Bring me Back") {
self.model.pushed = false
}
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: MyBackButton(label: "Back!") {
self.model.pushed = false
})
}
}
struct MyBackButton: View {
let label: String
let closure: () -> ()
var body: some View {
Button(action: { self.closure() }) {
HStack {
Image(systemName: "chevron.left")
Text(label)
}
}
}
}
5 Comments
kangarooChris
not working for me for some reason. Also, why do you use binding var $model in "is active", but not for self.model.pushed = false. What's the difference between the two?
kangarooChris
actually, I get this now. In self.model.pushed you are changing the value and in the other one you are observing it.
kangarooChris
Never seen this definition in root controller ....rootView: ContentView().environmentObject(Model())). what if you have more than one model? how do you declare that?
kangarooChris
In the log it says nothing and when I press the button nothing happens.
cahyo
Hi @Dhaval here you use the value of
@Published var pushed = false to Push or Pop between 2 View. What if when i need to do with many Views? Should i create new property same as pushed ?