我想在SwiftUI中关闭模式视图,但我不能
这是我的代码:
ContentView:
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()
}
}
我试图用一个状态创建一个非常简单的新项目来调用模式,菜单,模式和两个按钮,并且效果很好。我不明白为什么在上面的代码中它不起作用
有人遇到过同样的问题吗?
答案 0 :(得分:0)
您应该从ModalView
绑定presentationMode。
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")
})
}
}
}