我想在SwiftUI中取消一个模态视图,但我就是不能
这是我的代码:
内容视图:
import SwiftUI
enum Destination {
case modal
}
struct ContentView: View {
@Environment(\.presentationMode) var presentationMode
@State private var showModal = false
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack{
SubscribeButtonView(buttonTitle: "Modal", destination: .modal, showModal: $showModal)
.padding(.top, 50)
.padding(.leading, 30)
.padding(.trailing, 30)
Spacer()
}
}
.navigationBarTitle(Text("Menu"))
}
}
}
ModalView:
import SwiftUI
struct ModalView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading) {
Spacer()
SaveButtonView(origin: .modal)
Spacer()
}
.padding(.leading, 20)
.padding(.trailing, 20)
}
.navigationBarTitle("Modal")
.navigationBarItems(trailing: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
})
}
}
}
SubscribeButtonView:
import SwiftUI
struct SubscribeButtonView: View {
@Environment(\.presentationMode) var presentationMode
var buttonTitle: String
var destination: Destination
@Binding var showModal: Bool
var body: some View {
Button(action: {
self.showModal.toggle()
}) {
HStack {
Image(systemName: "plus.circle")
.font(.body)
Text(buttonTitle)
}
}.sheet(isPresented: $showModal) {
if self.destination == .modal {
ModalView()
}
}
.padding()
}
}
SaveButtonView:
import SwiftUI
struct SaveButtonView: View {
@Environment(\.presentationMode) var presentationMode
var origin: Destination
var body: some View {
Button(action: {
//THIS IS NOT WORKING
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Text("Save")
}
}
.padding()
}
}
我试着创建一个非常简单的新项目,只有一个状态来调用模式、菜单、模式和两个按钮,它工作得很好。我不明白为什么上面的代码不起作用
有人有同样的问题吗?
您应该将演示模式绑定到ModalView
struct SaveButtonView: View {
//@Environment(\.presentationMode) var presentationMode
@Binding var presentationMode : PresentationMode
var origin: Destination
var body: some View {
Button(action: {
//THIS IS NOT WORKING
self.$presentationMode.wrappedValue.dismiss()
}) {
HStack {
Text("Save")
}
}
.padding()
}
}
struct ModalView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading) {
Spacer()
SaveButtonView( presentationMode: self.presentationMode, origin: .modal)
Spacer()
}
.padding(.leading, 20)
.padding(.trailing, 20)
}
.navigationBarTitle("Modal")
.navigationBarItems(trailing: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
})
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。