We could use SwiftUI to pop a View to another, like this
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: PopView(),
label: {
Text("Pop View")
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct PopView:View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Button(
"Back",
action: { self.presentationMode.wrappedValue.dismiss() }
)
}
}
This will create a button, when you press the button, a new pop up, like below.
,
Stacked NavigationBars
import SwiftUI
struct PopSwiftUIView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
NavigationView {
Button(
"Back",
action: { self.presentationMode.wrappedValue.dismiss() }
).toolbar(content: {
Button(action: { }, label: {
Text("Done")
})
})
}
}
}
struct PopSwiftUIView_Previews: PreviewProvider {
static var previews: some View {
PopSwiftUIView()
}
}
Above code will run like this, you can see the Done
button is stacked to a lower level.
That is because you should only use NavigationView
one time. You don't need to use it again if you previously used it.
However, in this case, you need to add NavigationView
to preview yourself.
import SwiftUI
struct PopSwiftUIView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Button(
"Back",
action: { self.presentationMode.wrappedValue.dismiss() }
).toolbar(content: {
Button(action: { }, label: {
Text("Done")
})
})
}
}
struct PopSwiftUIView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PopSwiftUIView()
}
}
}
Back
Button
Hide Use .navigationBarBackButtonHidden(true)
to hide the back button.