Okay, this is a fun challenge! We need to make sure 1 minute exactly equals 100 subdivisions, which means each subdivision is 0.6 seconds (60 seconds / 100 subdivisions = 0.6 seconds).
Here's a SwiftUI stopwatch app that does exactly that:
swift
import SwiftUI
struct ContentView: View {
// MARK: - State Variables
@State private var isRunning = false // True if the stopwatch is currently running
@State private var startTime: Date? = nil // The date when the stopwatch started
@State private var elapsedMilliseconds: Int = 0 // Total elapsed milliseconds since start/reset
@State private var displayMinutes: Int = 0 // Minutes to display
@State private var displaySubdivisions: Int = 0 // Subdivisions to display
// MARK: - Timer Setup
// The timer fires every 10 milliseconds (0.01 seconds) for smooth updates.
// This precision is much higher than our 0.6-second subdivision, ensuring a smooth display.
let timer = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
// MARK: - Constants for Calculation
// 1 subdivision = 60 seconds / 100 = 0.6 seconds = 600 milliseconds
let subdivisionDurationMs: Int = 600
// MARK: - Body (UI Layout)
var body: some View {
VStack {
Spacer()
// Time Display
Text(String(format: "%02d:%02d", displayMinutes, displaySubdivisions))
.font(.system(size: 80, weight: .bold, design: .monospaced)) // Monospaced for consistent digit width
.foregroundColor(.primary)
.padding()
.background(Color.secondary.opacity(0.1))
.cornerRadius(20)
Spacer()
// Control Buttons
HStack(spacing: 30) {
// Start/Stop Button
Button(action: {
if isRunning {
stopTimer()
} else {
startTimer()
}
}) {
Text(isRunning ? "Stop" : "Start")
.font(.title2)
.fontWeight(.semibold)
.padding(.vertical, 15)
.padding(.horizontal, 30)
.frame(minWidth: 150)
.background(isRunning ? Color.red.opacity(0.8) : Color.green.opacity(0.8))
.foregroundColor(.white)
.cornerRadius(30)
.shadow(radius: 5)
}
// Reset Button
Button(action: resetTimer) {
Text("Reset")
.font(.title2)
.fontWeight(.semibold)
.padding(.vertical, 15)
.padding(.horizontal, 30)
.frame(minWidth: 150)
.background(Color.blue.opacity(0.8))
.foregroundColor(.white)
.cornerRadius(30)
.shadow(radius: 5)
}
// Disable reset if the stopwatch is running or already at 00:00
.disabled(isRunning && elapsedMilliseconds == 0)
.opacity((isRunning && elapsedMilliseconds == 0) ? 0.5 : 1.0)
}
.padding(.bottom, 50)
}
.onReceive(timer) { _ in
// This block is executed every time the `timer` fires
if isRunning, let start = startTime {
// Calculate total elapsed milliseconds since the start time
elapsedMilliseconds = Int(Date().timeIntervalSince(start) * 1000)
// Update the displayed time based on elapsed milliseconds
updateDisplayTime()
}
}
}
// MARK: - Timer Control Functions
private func startTimer() {
if !isRunning {
startTime = Date() // Record the exact moment the timer starts
isRunning = true
}
}
private func stopTimer() {
isRunning = false
// When stopping, `elapsedMilliseconds` will hold the value from the last `onReceive` update.
// If you wanted a "pause" feature, you'd add `elapsedMilliseconds` to a total, and reset `startTime` to `nil`
// or a new `Date` for the continuation, but for a simple stop/start, this is sufficient.
}
private func resetTimer() {
isRunning = false
startTime = nil
elapsedMilliseconds = 0 // Clear total elapsed time
updateDisplayTime() // Update display to 00:00
}
// MARK: - Time Calculation Function
private func updateDisplayTime() {
// Calculate the total number of custom subdivisions that have passed
let totalSubdivisions = elapsedMilliseconds / subdivisionDurationMs
// Calculate minutes (integer division: 100 subdivisions make 1 minute)
displayMinutes = totalSubdivisions / 100
// Calculate remaining subdivisions (modulo operator: the remainder after full minutes)
displaySubdivisions = totalSubdivisions % 100
}
}
// MARK: - Preview Provider
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
How to Use in Xcode:
Create a New Xcode Project: Open Xcode, select "App" under "iOS", click "Next".
Project Name: Give it a name like "MyStopwatchApp".
Interface: Select "SwiftUI".
Language: Select "Swift".
Save: Choose a location and create the project.
Replace ContentView.swift: Open the ContentView.swift file in your new project and replace its entire contents with the code provided above.
Run: Build and run the app on a simulator or a physical device (Cmd+R or click the Play button).
Explanation:
@State Variables:
isRunning: A boolean to track if the stopwatch is active.
startTime: Stores the Date object when the stopwatch started. This is crucial for calculating the elapsed time accurately.
elapsedMilliseconds: This is our internal, precise counter. We track time in milliseconds because it's a common, granular unit, and then convert it to our custom minute/subdivision format for display.
displayMinutes, displaySubdivisions: These hold the values that are actually shown on the screen.
timer (Timer.publish):
Timer.publish(every: 0.01, on: .main, in: .common).autoconnect(): This creates a publisher that emits a value every 0.01 seconds (10 milliseconds). We use this frequent update to ensure the display feels smooth, even though our "subdivision" unit is 600ms. .autoconnect() starts the timer automatically when the view appears.
subdivisionDurationMs:
This constant is 600. Why? Because 1 minute = 60 seconds = 60,000 milliseconds. If 1 minute has 100 subdivisions, then each subdivision is 60,000 ms / 100 = 600 ms. This is the core calculation.
onReceive(timer):
This SwiftUI modifier listens for events from our timer publisher.
Inside this block, if isRunning is true and we have a startTime, we calculate the elapsedMilliseconds by finding the timeIntervalSince the startTime (which is in seconds) and multiplying by 1000.
Then, updateDisplayTime() is called to convert these raw milliseconds into our custom minutes and subdivisions.
updateDisplayTime():
totalSubdivisions = elapsedMilliseconds / subdivisionDurationMs: This line calculates how many of our custom subdivisions have passed in total.
displayMinutes = totalSubdivisions / 100: Since 100 subdivisions make a minute, integer division gives us the full minutes.
displaySubdivisions = totalSubdivisions % 100: The modulo operator (%) gives us the remainder, which are the subdivisions currently being counted within the current minute.
This app provides a clean and functional stopwatch with your specific minute/subdivision requirement!
Buttons (startTimer, stopTimer, resetTimer):
These functions handle the state changes (isRunning, startTime, elapsedMilliseconds) that control the stopwatch's behavior.
UI (Text and Button):
Text(String(format: "%02d:%02d", displayMinutes, displaySubdivisions)): This formats the time. %02d ensures that numbers like "1" are displayed as "01", giving a consistent look (e.g., "00:00", "01:05").
The buttons change their text and background color based on the isRunning state.
The "Reset" button is disabled if the stopwatch is running and the time is 00:00, preventing accidental resets when nothing has been timed yet.