For this app, you’ll present three programming languages. Users will vote for their favorite programming language by tapping the logo. When the user taps a logo, the counter beneath it will increase.
To get started, open up Swift Playgrounds and create a new app. In the resources, you’ll find three images. Drag those images into the Playground app.
First, create some counter variables.
var csharp = 0
var kotlin = 0
var swift = 0
These will keep track of each time the user taps the button. Now to create the buttons. We’ll start with one and then copy it.
Add the following:
VStack {
Button {
// increase counter here
} label: {
Image("CSharp")
}
Text("\(csharp)")
.font(.headline)
}
Here’s our button. We’ll add the incrementing code momentarily. The label is the CSharp image. Underneath is a simple Text that shows the counter.
Now we want three buttons side by side. Create a containing HStack. Add the following;
HStack {
}
Now add two other buttons.
VStack {
Button {
// increase counter here
} label: {
Image("Kotlin")
}
Text("\(kotlin)")
.font(.headline)
}
VStack {
Button {
// increase counter here
} label: {
Image("Swift")
}
Text("\(swift)")
.font(.headline)
}
The buttons are all pushed against each other. Add the following modifier to each VStack.
.padding(.horizontal, 10)
Now each button has some good spacing. And look at that - we have an app. Okay, now let’s increase the counter of the CSharp when the user taps the button. Add the following:
Button {
csharp = csharp + 1
} label: {
Image("csharp")
}
csharp = csharp + 1
You’ll see we get an error. The error is telling us that we can’t update the variable directly from SwiftUI. Rather, we need to use something known as a property wrapper. Specifically a State property wrapper.
Update the variables to the following:
@State var csharp = 0
@State var kotlin = 0
@State var swift = 0
By setting the variables as state variables, we can change them in SwiftUI and when changed, the variable informs SwiftUI to recreate the interface. Try tapping on the Csharp button and you’ll see it increase.
Now update kotlin button:
Button {
kotlin = kotlin + 1
} label: {
Image("kotlin")
}
And the Swift button:
Button {
swift = swift + 1
} label: {
Image("swift")
}
Now tap all the buttons. We now have a working poll.