I have my main view calling a subview as a .sheet modal in SwiftUI. There is a form in the sheet that the user fills out. A button at the bottom is supposed to write the data to Core Data and dismiss the modal. When I run the code without the Core Data write, it dismisses the modal without any issue. When I include the Core Data code, it writes it successfully but does not dismiss the modal. I've tried debugging it by incorporating @Environment as a pass through variable, using @Binding, and using various print statements to make sure the dismiss fires. I am not getting any errors, but the modal never disappears via the button.
Here is the relevant code fragment for the Main View:
.sheet(isPresented: $showingSheet) {AddListItem(listName: "", favoriteFlag: false)
And here is the full code for the Sub View that shows the modal:
struct AddListItem: View {
@State var listName: String
@State var favoriteFlag: Bool
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) private var viewContext
var body: some View {
VStack {
Form {
Section(header: Text("List Details")) {
TextField("List Name", text: $listName)
Toggle(isOn: $favoriteFlag) {
Text("Favorite?")
}
}
}
HStack {
Button(action: {
withAnimation {
let newItem = Item(context: self.viewContext)
newItem.timestamp = Date()
do {
try self.viewContext.save()
self.presentationMode.wrappedValue.dismiss()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
//self.presentationMode.wrappedValue.dismiss()
}) {
Text("Add Tasks to \(listName)")
}
}
.navigationBarTitle("Create New List")
}
}
}
I've reviewed some similar questions here on Stack Overflow, but haven't been able to find a solution. I feel like I am missing something simple here... appreciate the help!