
Here’s a simple counter app using SwiftUI that increments a counter each time a button is pressed:
import SwiftUI
struct CounterView: View {
// State to hold the count
@State private var count = 0
var body: some View {
VStack {
Text("Counter: \(count)")
.font(.largeTitle)
.padding()
Button(action: {
// Action to increment the count
count += 1
}) {
Text("Increment")
.font(.headline)
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(10)
}
.padding()
}
}
}
import SwiftUI
@main
struct CounterApp: App {
var body: some Scene {
WindowGroup {
CounterView()
}
}
}
Explanation:
- CounterView Struct:
@State private var count = 0
: Defines a state propertycount
to hold the current count value. The@State
property wrapper is used here because changes tocount
will cause SwiftUI to update the view automatically.Text("Counter: \(count)")
: Displays the current value ofcount
.Button(action: { ... }) { ... }
: Creates a button labeled “Increment” with an action closure that increments thecount
by 1 when pressed.
- Button Styling:
.font(.headline)
: Sets the font size to headline..padding()
: Adds padding around the button text..foregroundColor(.white)
: Sets the text color to white..background(Color.blue)
: Sets the background color to blue..cornerRadius(10)
: Rounds the corners of the button.
- CounterApp Struct:
WindowGroup
: Sets up the main window of the app withCounterView
as its root view.
How to Use:
- Copy the above code into a SwiftUI project in Xcode.
- Run the project on a simulator or device.
- You should see a screen with “Counter: 0” and a button labeled “Increment”.
- Each time you tap the “Increment” button, the counter value should increase by one.