我正在尝试做最简单的事情。我只想以编程方式调用新的SwiftUI视图-而不是按钮,而是代码。我已经阅读了数十篇有关此问题的文章和Apple文档-但我发现的几乎所有内容都与已重命名或不推荐使用的代码有关。我找到的最接近的是:
NavigationLink(destination: NewView(), isActive: $something) {
EmptyView()
}
但这在Xcode Beta 7中对我不起作用。这是简单的应用程序:
struct ContentView: View {
@State private var show = false
var body: some View {
VStack {
Text("This is the ContentView")
Toggle(isOn: $show) {
Text("Toggle var show")
}
.padding()
Button(action: {
self.show = !self.show
}, label: {
Text(self.show ? "Off" : "On")
})
Text(String(show))
//this does not work - the ContentView is still shown
NavigationLink(destination: SecondView(), isActive: $show)
{
EmptyView()
}
//this does not work - it adds SecondView to ContentView
//I want a new view here, not an addition
//to the ContentView()
// if show {
// //I want a new view here, not an addition to the ContentView()
// SecondView()
// }
}
}
}
残酷的目的地:
struct SecondView: View {
var body: some View {
Text("this is the second view!")
}
}
我一定错过了非常简单的东西。任何指导将不胜感激。 iOS 13.1,Catalina 19A546d,Xcode 11M392r
答案 0 :(得分:2)
几件事。首先,必须将NavigationLink嵌入到NavigationView中才能工作。其次,该链接不需要您显示的视图。这应该显示第二个视图。我将请您更新其他元素。
var body: some View {
NavigationView{
VStack {
Text("This is the ContentView")
Toggle(isOn: $show) {
Text("Toggle var show")
}
.padding()
Button(action: {
self.show = !self.show
}, label: {
Text(self.show ? "Off" : "On")
})
Text(String(show))
//this does not work - the ContentView is still shown
NavigationLink(destination: SecondView()){
Text("Click to View")}
Spacer()
// {
// EmptyView()
// }
//this does not work - it adds SecondView to ContentView
//I want a new view here, not an addition
//to the ContentView()
// if show {
// //I want a new view here, not an addition to the ContentView()
// SecondView()
// }
}
}
}