Alert
Jan 6, 2024
- 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
2. Add .alert next to the button
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
- 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
- We can add an action inside the .destructive braces
- Create a color variable and add that into a rounded rectangle
- We add a function inside the
action:{…}
5. Extract the whole Alert
- We will extract the function, and add the function inside to the content
- Add getAlert into the .alert()
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
- Add a string value into the getAlert() function
- We specify the string value inside the buttons