In iPhone apps, there comes a time when you might need to show an alert to a user to ask them for input. Apple provides the alert instance method on a view for you to use. This particular instance method is for iOS 15 and later. Here is how you use it:
struct ContentView: View {
@State private var showAlert = false
var body: some View {
VStack {
Button("Show Alert") {
showAlert.toggle()
}
.alert(
"Important Message", // Title of the alert
isPresented: $showAlert, // Binding to show the alert
actions: {
Button("Allow") {
// Action when "Allow" button is pressed
print("User pressed Allow")
}
Button("Don't Allow", role: .destructive) {
// Action when "Don't Allow" button is pressed
print("User pressed Don't Allow")
}
},
message: {
Text("Do you want to allow this action?")
}
)
.padding()
}
}
}
We first create a variable that contains a bool. It is called showAlert and uses the @State property wrapper, which means that when the value changes, the view will refresh.
In our body we create a VStack and in there we have a Button view that when tapped, toggles the showAlert from false to true and so on.
We then add the .alert to the Button view and provide it a title, in this case “Important Message”.
Next, we use the isPresented and bind it to $showAlert. The alert will show depending on if $showAlert is true or false.
We then add our actions which are Button views. The first button we label “Allow”, and the second button “Don’t Allow”. Add more, or less, buttons as needed with your own titles.
When you tap one of these buttons, the alert dismisses and you can tap the Button view again to show the alert again.
Leave a Reply
You must be logged in to post a comment.