由于 SwiftUI 是声明式的,因此没有dismiss
方法。
如何添加关闭/关闭按钮DetailView
?
struct DetailView: View {
var body: some View {
Text("Detail")
}
}
struct ContentView : View {
var body: some View {
PresentationButton(Text("Click to show"), destination: DetailView())
}
}
使用@State属性包装器(推荐)
struct ContentView: View {
@State private var showModal = false
var body: some View {
Button("Show Modal") {
self.showModal.toggle()
}.sheet(isPresented: $showModal) {
ModalView(showModal: self.$showModal)
}
}
}
struct ModalView: View {
@Binding var showModal: Bool
var body: some View {
Text("Modal view")
Button("Dismiss") {
self.showModal.toggle()
}
}
}
使用演示模式
您可以使用presentationMode
模态视图中的环境变量并调用self.presentaionMode.wrappedValue.dismiss()
关闭模式:
struct ContentView: View {
@State private var showModal = false
// If you are getting the "can only present once" issue, add this here.
// Fixes the problem, but not sure why; feel free to edit/explain below.
@SwiftUI.Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
var body: some View {
Button(action: {
self.showModal = true
}) {
Text("Show modal")
}.sheet(isPresented: self.$showModal) {
ModalView()
}
}
}
struct ModalView: View {
@Environment(\.presentationMode) private var presentationMode
var body: some View {
Group {
Text("Modal view")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Dismiss")
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)