App 2 — 24 Apps You Can Make Today
Scoreboard
Keep score for two players with + and − buttons. @State for numbers, updated by taps.
- ios
A scoreboard for two. Each player gets a score, a button to add a point, and a button to subtract one. The score on screen updates instantly when you tap.
What you'll build
Two columns — one per player — each showing a name, a large score number, and +/− buttons. Tap a button and the number changes immediately.
Key concepts
@State with Int — The score is just a number. @State var score = 0 and SwiftUI takes care of redrawing when it changes.
@State var playerOneScore = 0
@State var playerTwoScore = 0
Buttons that do math — The button's action closure is just Swift. Add or subtract right there.
Button("+") {
playerOneScore += 1
}
Button("−") {
playerOneScore -= 1
}
HStack and VStack — Stack views horizontally to put players side by side, vertically to stack name, score, and buttons within each column.
HStack(spacing: 40) {
VStack { /* Player 1 */ }
VStack { /* Player 2 */ }
}
.font(.system(size:weight:)) — Make the score number big so it reads from across a room.
Two players, two pieces of state
Notice that each player has their own @State variable. That's the pattern: one piece of state per thing that changes independently. When player one's score updates, player two's column doesn't re-render unnecessarily.
Download and run it
Open the Playgrounds file from GitHub, hit Run, and keep score.