SwiftUI: How to Show Alert & ActionSheet in SwiftUI

Alert & ActionSheet in SwiftUI is a pop-up that shows in the center and bottom of the device which contains some title, message, and buttons. Buttons trigger some actions based on your needs.
Alert in SwiftUI is same like UIAlertController in UIKit.
In this tutorial, we will see how we can show Alert & ActionSheet in SwiftUI.
Here’s is the video if you prefer video over text.
Prerequisite:
You need macOS Catalina and or above in order to have SwiftUI work in the simulator.
1. Create a New SwiftUI Project
Open Xcode, Select Single View Application and click on next and give a proper name to the project and make sure to select the user interface should be SwiftUI, and create the project.

2. Simple Alert
Alert without message & action-handler.
@State var simpleAlert = falseButton("Simple Alert") {
simpleAlert.toggle()
}.alert(isPresented: $simpleAlert, content: {
Alert(title: Text("Simple Alert"))
})

3. Alert with Message & Action Handler
Alert with message & Action-handler.
@State var simpleAlertMessage = falseButton("Simple Alert With message") {
simpleAlertMessage.toggle()
}.alert(isPresented: $simpleAlertMessage, content: { Alert(title: Text("Simple Alert With message"),
message: Text("Simple alert With message"),
dismissButton: Alert.Button.default(Text("Press this"),
action: {
message = "Button clicked"
}))
})

4. Alert with Multiple Buttons
Alert with Multiple Buttons and their handlers.
@State var simpleAlertMessageWithButtons = falseButton("Simple Alert With Title and Button") {
simpleAlertMessageWithButtons.toggle()
}.alert(isPresented: $simpleAlertMessageWithButtons, content: {
let firstButton = Alert.Button.default(Text("First"))
let secondButton = Alert.Button.destructive(Text("Second")) {
message = "Second Button Clicked"
}
return Alert(title: Text("Simple Alert With Title and Button"), primaryButton: firstButton, secondaryButton: secondButton)
})

5. ActionSheet in SwiftUI
@State var simpleActionSheet = false
@State var message = ""Button("Simple ActionSheet") {
simpleActionSheet.toggle()
}.actionSheet(isPresented: $simpleActionSheet, content: {
let action1 = ActionSheet.Button.default(Text("First action")) {
message = "Action Sheet first action clicked"
}
let action2 = ActionSheet.Button.default(Text("Second action")) {
message = "Action Sheet second clicked"
}
return ActionSheet(title: Text("Action Sheet"), message: Text("Message"), buttons: [action1, action2])
})

I hope you like this tutorial and if you want any help let me know in the comment section.- there is way more to come! You can follow me on, and do not miss out on all future Articles and Video tutorials.
I am really happy you read my article! If you have any suggestions or improvements of any kind let me know! I’d love to hear from you! 😊
Originally published at https://letcreateanapp.com on January 16, 2021.