我在NavigationBar
上嵌入了一个按钮。
我试图使按钮打开一个名为View
的新DetailView
我尝试使用NavigationLink
,但是它在按钮内不起作用。
import SwiftUI
struct ContentView: View {
@ObservedObject var dm: DataManager
@State var isAddPresented = false
var body: some View {
NavigationView {
HStack {
List () {
ForEach (dm.storage) { data in
StileCella(dm2: data)
}
}
.navigationBarTitle("Lista Rubrica")
.navigationBarItems(trailing: Button(action: {
self.isAddPresented = true
// Load here the DetailView??? How??
DetailView()
}) {
Text("Button")
})
}
}
}
}
struct DetailView: View {
var body: some View {
VStack(alignment: .center) {
Text("CIAO").bold()
Spacer()
Image(systemName: "star")
.resizable()
}
}
}
答案 0 :(得分:1)
您只需要在视图中添加一个工作表修饰符,即可根据isAddPresented的值显示视图,就像这样:
struct ContentView: View {
@State var isAddPresented = false
var body: some View {
NavigationView {
List(dm.storage){ data in
StileCella(dm2: data)
}
.navigationBarTitle("Lista Rubrica")
.navigationBarItems(trailing: Button("Button") {
self.isAddPresented = true
})
} .sheet(isPresented: $isAddPresented,
onDismiss: { self.isAddPresented = false }) {
DetailView()
}
}
}
重要的一点是要记住在关闭时将isAddPresented设置为false,以防止它再次出现。
答案 1 :(得分:1)
如果您要像打开故事板一样打开新视图(而不是通过图纸),则可以通过以下方式更新代码:
import SwiftUI
struct ContentView: View {
@ObservedObject var dm: DataManager
@State var isAddPresented = false
var body: some View {
NavigationView {
HStack {
List () {
ForEach (dm.storage) { data in
StileCella(dm2: data)
}
}
.navigationBarTitle("Lista Rubrica")
.navigationBarItems(leading:
NavigationLink(destination: DetailView()) {
Text("Button")
})
}
}
}
}
struct DetailView: View {
var body: some View {
VStack(alignment: .center) {
Text("CIAO").bold()
Spacer()
Image(systemName: "star")
.resizable()
}
}
}
代替按钮,只需在navigationBarItems内添加NavigationLink。这样就可以了!我写了完整的指南,但主要的改变是,我使用了
.navigationBarItems(leading:
NavigationLink(destination: DetailView()) {
Text("Button")
})
代替:
.navigationBarItems(trailing: Button(action: {
self.isAddPresented = true
// Load here the DetailView??? How??
DetailView()
}) {
Text("Button")
})