Reputation: 551
So I found this amazing piece of code which uses presentationMode
environment variable to archive transition between views without NavigationView:
import SwiftUI
struct View2: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("POP")
}
}
.navigationBarTitle("")
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
}
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: View2()) {
Text("PUSH")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
but when I wrap it in another View (which is what I need to do in my own app):
import SwiftUI
struct View2: View {
@SwiftUI.Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("POP")
}
}
.navigationBarTitle("")
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
}
struct Playground: View {
var index: Int
var body: some View {
NavigationView {
NavigationLink(destination: View2()) {
Text("PUSH #\(index)")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
}
struct Playgrounds: View {
var body: some View {
VStack {
Text("List of bush buttons").font(.title)
List(0..<5, id: \.self) { index in
HStack {
Playground(index: index)
}
}
}
}
}
struct Playground_Previews: PreviewProvider {
static var previews: some View {
Playgrounds()
}
}
I can only see a list of "back" buttons (without their labels!):
instead of a list of "Push #1", "Push #2" etc (which should open View2 onClick event). How can I fix it?
Upvotes: 2
Views: 2419
Reputation: 991
You only need one NavigationView
instead of defining a NavigationView
for each NavigationLink
:
struct Playground: View {
var index: Int
var body: some View {
NavigationLink(destination: View2()) {
Text("PUSH #\(index)")
}
}
}
struct Playgrounds: View {
var body: some View {
NavigationView {
VStack {
Text("List of bush buttons").font(.title)
List(0..<5, id: \.self) { index in
HStack {
Playground(index: index)
}
}
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
Upvotes: 1