create a simple stopwatch using swiftui in swift

To create a simple stopwatch using SwiftUI and Timer in Swift, follow the steps below:

  1. Create a new SwiftUI view file and name it "StopwatchView.swift".
  2. Import the SwiftUI and Combine frameworks at the top of the file:
main.swift
import SwiftUI
import Combine
30 chars
3 lines
  1. Add the following properties to the view:
main.swift
@State private var secondsElapsed = 0
@State private var timer: Timer?
71 chars
3 lines
  1. Add a Text view to display the time:
main.swift
Text("\(secondsElapsed)")
    .font(.largeTitle)
    .foregroundColor(.black)
78 chars
4 lines
  1. Add two buttons to start and stop the timer:
main.swift
HStack {
    Button(action: startTimer) {
        Text("Start")
    }
    Button(action: stopTimer) {
        Text("Stop")
    }
}
131 chars
9 lines
  1. Implement the "startTimer" and "stopTimer" methods:
main.swift
private func startTimer() {
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
        secondsElapsed += 1
    }
}

private func stopTimer() {
    timer?.invalidate()
    timer = nil
}
210 chars
11 lines

That's it! Your simple stopwatch is now ready. The full code for the StopwatchView.swift file is shown below:

main.swift
import SwiftUI
import Combine

struct StopwatchView: View {
    @State private var secondsElapsed = 0
    @State private var timer: Timer?
    
    var body: some View {
        VStack {
            Text("\(secondsElapsed)")
                .font(.largeTitle)
                .foregroundColor(.black)
            
            HStack {
                Button(action: startTimer) {
                    Text("Start")
                }
                Button(action: stopTimer) {
                    Text("Stop")
                }
            }
        }
    }
    
    private func startTimer() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            secondsElapsed += 1
        }
    }
    
    private func stopTimer() {
        timer?.invalidate()
        timer = nil
    }
}
814 chars
36 lines

gistlibby LogSnag