How to show alert in SwiftUI (iOS 15+)

DevTechie
DevTechie
Published in
5 min readSep 2, 2022

--

Starting iOS 15 and above, Alert has been moved into presentation modifiers area meaning it’s now an alert modifier rather than a struct.

In this article, we will explore alerts in SwiftUI for iOS 15+.

alert modifier is used to show an alert when we want the user to act in response to the state of the app.

To show an alert, we create a boolean state variable which determines if the alert should be visible or not.

@State private var showAlert = false

From there, we attach alert modifier passing State variable as isPresented parameter along with the buttons we want to show in the alert.

.alert("This is an alert", isPresented: $showAlert) { 
Button("OK") {}
Button("Not OK") {}
}

We launch the alert by toggling the State variable.

showAlert.toggle()

Complete code:

struct DevTechieAlertsExample: View {
@State private var showAlert = false
var body: some View {
NavigationView {
VStack {
Text("Learn iOS with DevTechie")
.font(.largeTitle)
.foregroundColor(.white)
.padding()
.background(.orange, in…

--

--