[英]Creating a NavigationLink in SwiftUI without NavigationView
So I found this amazing piece of code which uses presentationMode
environment variable to archive transition between views without NavigationView:所以我发现了这段惊人的代码,它使用presentationMode
环境变量来存档没有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).而不是“Push #1”、“Push #2”等列表(应该打开 View2 onClick 事件)。 How can I fix it?我该如何解决?
You only need one NavigationView
instead of defining a NavigationView
for each NavigationLink
:你只需要一个NavigationView
,而不是定义NavigationView
每个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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.