gpt4 book ai didi

SwiftUI 关闭模式

转载 作者:行者123 更新时间:2023-11-29 05:09:21 32 4
gpt4 key购买 nike

由于 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")
}
}
}
}

enter image description here

关于SwiftUI 关闭模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59832011/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com