If you need to create a simple alert popup, read Paul Hudson’s post. (The post also covers how to create alerts in the newer, iOS-15 way.)
I needed a way for a single view to show alerts with one button, with two buttons, and with two buttons and a destructive action (destructive actions are shown in red). I came up with a solution for Fasty, then I wanted to use it in another project, so I put it in a package.
To use:
- Import the package
- Add “@State private var alertParams: AlertParams?” to the view that you want to have the Alert.
- At the bottom of that view, add: “.modifier(AlertModifier(alertParams: $alertParams))”
- Add the following (or something similar) to the view: Button(“Pop up an alert with one button and an action”) { alertParams = AlertParams(title: “One Button”, message: “One button that calls an action”, primaryButtonLabel: “The button label”) { print(“The user clicked the Alert button”) } }
import SwiftUI
import AlertPopUp_iOS13
struct ContentView: View {
@State private var alertParams: AlertParams?
var body: some View {
VStack {
Button("Pop up an alert with one button and an action") {
alertParams = AlertParams(title: "One Button", message: "One button that calls an action", primaryButtonLabel: "The button label") { print("The user clicked the Alert button") }
}
}
.modifier(AlertModifier(alertParams: $alertParams))
.padding()
}
}
The readMe gives more details.