Homework 5: State Variables

Toggle an Image

  1. Create a new Xcode project, paste in the buttonStyle from the previous lesson (Homework 4), and use it to style a new button.
  2. Add a new @State boolean variable and set its initial value to false.
  3. Download http://nmi.cool/appdev/wp-content/uploads/sites/10/2022/08/quixote.zip , unzip the file, and drag both images into Asssets.xcassets.
  4. Add a toggle statement to your button’s action that changes the value of your boolean variable each time the button is tapped.
  5. The images that you just added are named dq1.jpg and dq2.jpg. Wrap a Vstack around your button and OUTSIDE of the button, add an Image that displays one of those images when the value of your boolean variable is false and the other image when the value is true. If you follow the textbook example as a guide, this is easy!

Increment a value

  • In the same project, create a new integer state variable and set its value to 0. For example:
@State var Numb = 0 
  • Underneath the image (inside of the same VStack), add a text field to display the value of the variable you just created. For example:
Text("\(self.Numb)")
  • SwiftUI buttons can have multiple actions that, literally do many things at once. To demonstrate “Button Power,”  add a brand new action to the same button that causes the images to toggle, underneath the toggle action. 
  • This new action will increment the value of your integer variable by two each time the button is tapped. Put that action right underneath the toggle command.