Skip to content
DeveloperMemos

Creating a Simple Counter in SwiftUI

SwiftUI, Counter, iOS Development1 min read

SwiftUI provides an intuitive and powerful way to build user interfaces for iOS applications. In this tutorial, we'll take a look at how to create a simple counter app using SwiftUI. Let's get started!

Setting Up the Project

First, open Xcode and create a new SwiftUI project. Name it "SimpleCounter" or choose a name that suits your preference. Once the project is set up, let's dive into the code.

Creating the Counter View

Open the ContentView.swift file, which contains the main view for our application. Replace the existing code with the following:

1import SwiftUI
2
3struct ContentView: View {
4 @State private var count = 0
5
6 var body: some View {
7 VStack {
8 Text("Counter: \(count)")
9 .font(.title)
10
11 HStack {
12 Button(action: {
13 count -= 1
14 }) {
15 Image(systemName: "minus.circle")
16 .font(.largeTitle)
17 }
18
19 Button(action: {
20 count += 1
21 }) {
22 Image(systemName: "plus.circle")
23 .font(.largeTitle)
24 }
25 }
26 }
27 }
28}
29
30struct ContentView_Previews: PreviewProvider {
31 static var previews: some View {
32 ContentView()
33 }
34}

Understanding the Code

In this code snippet, we define a @State property called count, which represents the value of our counter. The @State property wrapper allows SwiftUI to automatically update the view whenever the value of count changes.

Inside the body property, we create a VStack to vertically stack our views. The first view is a Text that displays the current value of the counter using string interpolation (\(count)). We also apply a font style of .title to make it more prominent.

Next, we create an HStack to horizontally stack two Button views. The first button decreases the count by 1 when tapped, and the second button increases it by 1. We use system images from SF Symbols (minus.circle and plus.circle) to represent the buttons and apply a larger font size using .largeTitle.

Running the App

Now, run the app in the simulator or on a physical iOS device. You should see the counter with two buttons to increment and decrement the value. Tap on the buttons, and you'll notice the counter updating accordingly.

Wrap Up

Congratulations! You have successfully created a simple counter app in SwiftUI. Feel free to customize the appearance and behavior of the counter further according to your preferences. The above example demonstrates the power and simplicity of SwiftUI in creating interactive user interfaces while leveraging the declarative nature of the framework. With just a few lines of code, you can build engaging and responsive apps.