SwiftUI_visionOS_Note

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

 
  1. Text(”There’s an error”) is the title of alert
  1. Bind the boolean variable to alert isPresented: $showAlert
  1. Write a button text in braces {Text(”Ok, fine”)}
 
 

3. Add two buttons in alert

  1. We bind boolean to alert, and add content Alert()
  1. title: is title of the Alert
  1. primaryButton has .destructive() and we add text inside
  1. secondaryButton will perform .cancel()
 

4. Add function inside the primary button

  • We can add an action inside the .destructive braces
 
  1. Create a color variable and add that into a rounded rectangle
 
  1. 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
 
  1. We create empty string varibles
 
  1. Add a string value into the getAlert() function
 
  1. We specify the string value inside the buttons
 
     

    You might also like

    BlogPro logo
    Made with BlogPro