Reputation: 21
I want to dismiss a modal view in SwiftUI, but I just can't
This is my code:
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"))
}
}
}
The 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")
})
}
}
}
The 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()
}
}
The 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()
}
}
I tried to create a really simple new project with just one state to call the modal, the menu, the modal and the two buttons and it worked just fine. I can't understand why it isn't working in the code above
Did anyone have this same issue?
Upvotes: 2
Views: 818
Reputation: 11531
You are supposed to bind the presentationMode from 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")
})
}
}
}
Upvotes: 3