Skip to content
Toggle an Image
- Create a new Xcode project, paste in the buttonStyle from the previous lesson (Homework 4), and use it to style a new button.
- Add a new @State boolean variable and set its initial value to false.
- Download http://nmi.cool/appdev/wp-content/uploads/sites/10/2022/08/quixote.zip , unzip the file, and drag both images into Asssets.xcassets.
- Add a toggle statement to your button’s action that changes the value of your boolean variable each time the button is tapped.
- 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.