Reputation: 11
I’m trying to show alerts in a sheet in SwiftUI. I have Cancel and Save buttons on the sheet and both of them are dismissed after the action is done.If there is an error on saving, an alert is pop upped. However, the sheet can not be dismissed after the alert is shown. Both save and cancel can not be dismissed after the alert dismiss is tapped. I can not figure out the reason. Any help would be appreciated. Thank you.
Related code
.navigationBarItems(
leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
.foregroundColor(Color("OrangeColor"))
.font(.custom("Montserrat-Medium", size: 18))
},
trailing:
Button(action: {
if selectedBook == nil {
errorInfo = AlertInfo( id: .bookNotSelectedError,
title: "Please choose a book",
message: "")
}
if quote.isEmpty {
errorInfo = AlertInfo( id: .quoteEmptyError,
title: "Please choose a quote",
message: "")
}
if let book = selectedBook {
// Save operations
}
self.presentationMode.wrappedValue.dismiss()
})
{
Text("Save")
.foregroundColor(Color("OrangeColor"))
.font(.custom("Montserrat-Medium", size: 18))
}
.alert(item: $errorInfo, content: { info in
Alert(title: Text(info.title),
message: Text(info.message))
})
)
Alert Info Struct
struct AlertInfo: Identifiable {
enum AlertType {
case saveError
case bookNotSelectedError
case quoteEmptyError
case totalPageError
case currentPageError
}
let id: AlertType
let title: String
let message: String
}
Upvotes: 1
Views: 724
Reputation: 12125
Your SAVE Button checks for errors but then always calls dismiss() – so the Alert shows up, but vanishes immediately. Also you have to check through the errors using ..else if...
This is how it should work:
Button(action: {
if selectedBook == nil {
errorInfo = AlertInfo( id: .bookNotSelectedError,
title: "Please choose a book",
message: "")
}
else if quote.isEmpty {
errorInfo = AlertInfo( id: .quoteEmptyError,
title: "Please choose a quote",
message: "")
}
else if let book = selectedBook {
// only call dismiss() after save was successful
presentationMode.wrappedValue.dismiss()
}
// NO dismiss here!
})
{
Text("Save")
}
Please also note that Alert and alert(item:content:) are deprecated.
Upvotes: 1