How to present an Alert in SwiftUI

ODENZA
2 min readFeb 6, 2021

--

In this article, I’m going to show you how to present an Alert with SwiftUI 2.0.
We can create an alert very easy in SwiftUI, code like this:

Alert(title: Text("Hello World!"))
struct AlertView: View {
@State var showAlert = false
var body: some View { HStack {
Button(action: {
self.showAlert.toggle()
}, label: {
Text("Show").padding(.trailing)
})
}.padding()
.alert(isPresented: $showAlert, content: {
Alert(title: Text("Alert Title!"))
})
}
}
.alert(isPresented: $showAlert, content: {    let title = Text("Alert Title!")
let message = Text("This is an important message")
Alert(title: title, message: message)})

To change the button’s text:

.alert(isPresented: $showAlert, content: {   let button = Alert.Button.default(Text("Close")) {
print("Button Pressed")
}
let title = Text("Alert Title!")
let message = Text("This is an important message")
return Alert(title: title, message: message, dismissButton: button)})
.alert(isPresented: $showAlert, content: {   let primaryButton = Alert.Button.default(Text("Primary")) {
print("primary button pressed")
}
let secondaryButton = Alert.Button.cancel(Text("Secondary")) {
print("secondary button pressed")
}
let title = Text("Title!")
let message = Text("This is an important message")
return Alert(title: title, message: message, primaryButton: primaryButton, secondaryButton: secondaryButton)})
.alert(isPresented: $showAlert, content: {   let primaryButton = Alert.Button.destructive(Text("Delete")) {
print("primary button pressed")
}
let secondaryButton = Alert.Button.cancel() let title = Text("Title!")
let message = Text("This is an important message")
return Alert(title: title, message: message, primaryButton: primaryButton, secondaryButton: secondaryButton)})

--

--

ODENZA
ODENZA

No responses yet