- Alerts are the quickest and simplest way to display a popup to users.
- To present the alert, toggle the boolean.
- Functions can be added within the alert action.
- You can customize alerts with empty strings by defining string values within the button action.
- Using an enum and switch allows for individual alert customization.
1. Create a button with boolean toggle
struct ContentView: View {
@State var showAlert: Bool = false
var body: some View {
Button("Click here"){
showAlert.toggle()
}
}
}
}
2. Add .alert next to the button
Button(){...}
.alert(Text("There's an error"), isPresented: $showAlert){
Text("Ok, fine")
}
Text(”There’s an error”)
is the title of alert
- Bind the boolean variable to alert
isPresented: $showAlert
- Write a button text in braces
{Text(”Ok, fine”)}
3. Add two buttons in alert
Button(){...}
.alert(isPresent: $showAlert){
Alert(
title: Text("Hello"),
primaryButton: .destructive(Text("Delete")),
secondaryButton: .cancel()
)
}
- We bind boolean to alert, and add content
Alert()
- title: is title of the Alert
- primaryButton has
.destructive()
and we add text inside
- secondaryButton will perform
.cancel()
4. Add function inside the primary button
primaryButton: .destructive(Text("Delete"), action:{...})
- We can add an action inside the .destructive braces
- Create a color variable and add that into a rounded rectangle
@State var backgroundColor: Color = Color.yellow
RoundedRectangle(...).frame(...).foregroundStyle(background)
- We add a function inside the
action:{…}
primaryButton: .destructive(Text(...), action:{
backgroundColor = .red
}
5. Extract the whole Alert
- We will extract the function, and add the function inside to the content
func getAlert() -> Alert {
return Alert(
title: Text("this is the title"),
message: Text("Here we will describe the error."),
primaryButton: .destructive(Text("DELETE"), action: {
backgroundColor = .red
}),
secondaryButton:. cancel())
}
- Add getAlert into the .alert()
.alert(isPresented: $showAlert){
getAlert()
}
6. Customize the alert
- We can use the alert function we just created and customize each button to have their own strings
- We create empty string varibles
@State var alertTitle: String = ""
@State var alertMessage: String = ""
- Add a string value into the getAlert() function
func getAlert() -> Alert {
return Alert(
title: Text(alertTitle),
message: Text(alertMessage),
primaryButton: .destructive(Text("DELETE"), action: {
backgroundColor = .red
}),
secondaryButton:. cancel())
}
- We specify the string value inside the buttons
HStack{
Button("Click here"){
alertTitle = "TITLE 1"
alertMessage = "MESSAGE 1"
showAlert.toggle()
}
Button("Click here"){
alertTitle = "TITLE 1"
alertMessage = "MESSAGE 1"
showAlert.toggle()
}
}
.alert(isPresented: $showAlert){
getAlert()
}