Adding actions to alert buttons
We may want to display alerts with more than just an OK button to confirm the alert has been read. In some cases, we may want to present a Yes or No choice to the user. For example, if the user wanted to delete an item in a list, we may want to present an alert where clicking on yes deletes the item and clicking on no does not change anything.
In this recipe, we will look at how to add a secondary button to alerts.
Getting ready
Create a SwiftUI app named AlertsWithActions
.
How to do it
We will implement an alert with two buttons and an action. The alert will get triggered by a tap gesture on some text. The steps are as follows:
- Create a
@State
variable that determines if the alert is displayed or not. Place the variable just below theContentView
struct declaration:@State private var changeText = false
- Create a
@State
variable to hold the text to be displayed on the screen. Give it an initial value ofTap to Change Text
:...