I want to share a cool strategy for handling multiple alerts. I got the idea from someone's post on Hacking with Swift (see here @bryceac's post: https://www.hackingwithswift.com/forums/swiftui/exporting-multiple-file-types/13298) about changing the document and document types for a file exporter in a view model. You can do the same things (in a lot of cases at least) for alerts. The simplest alerts just have an informative title and message. If you have a bunch of alerts you potentially need to display, you can change the Strings in a view model. For example, your actual alert code may look like this
.alert(isPresented: $viewModel.showingAlert) {
Alert(title: Text(viewModel.alertTitle), message: Text(viewModel.alertMessage), dismissButton: .default(Text("Got it.")))
}
Though this can result in some funny passing around of Strings if you need to update them in other places then your main view model, I find it works well (and I had trouble just adding different alerts to different views as Paul Hudson suggested on Hacking with Swift for whatever reason) and I like not having say, 10 alerts in the event that a lot of different results can occur of which you need to notify the user.
But I think using an enum is better, as John M (https://stackoverflow.com/users/3088606/john-m) suggested. For example:
enum AwesomeAlertType {
case descriptiveName1
case descriptiveName2
}
For simple alerts, you can have a function that builds them using a title and a message, and a button title with a default value of your choosing:
func alert(title: String, message: String, buttonTitle: String = "Got it") -> Alert {
Alert(title: Text(title), message: Text(message), dismissButton: .default(Text(buttonTitle)))
}
Then, you can use do something like the following:
.alert(isPresented: $viewModel.showingAlert) {
switch viewModel.alertType {
case descriptiveName1:
return alert(title; "My Title 1", message: "My message 1")
case descriptiveName2:
return alert(title; "My Title 2", message: "My message 2")
default:
return alert(title: "", message: "")
}
}
This lets you declare your alert UI in one block, control its state with an enum and a binding to a bool that can be assigned in view models, and keep your code short and DRY by using a function to produce basic alerts (sometimes all you need) with a title and a message, and a button with a title.
showFirstAlert
orshowSecondAlert
tofalse
!false
when the user dismisses the alert..alert
to show a message. (It reminds me of a problem withUIAlertView
's from UIKit-- and trying to use them at multiple levels in a view controller hierarchy).