App 12 — 24 Apps You Can Make Today

Hold On Contest

Hold a button as long as you can — a timer-based contest that tracks your best time.

  • ios
↓ Download Playgrounds File

How long can you hold on? This app runs a timer for as long as you keep your finger down. Let go, and your time is recorded. It's a contest against yourself.

What you'll build

A large button that starts a timer when you press it and stops when you lift your finger. Your current time and best time are shown on screen.

Key concepts

LongPressGesture vs drag/tap — For detecting the duration of a press, DragGesture(minimumDistance: 0) is often the most flexible tool — it fires onChanged every frame and onEnded when the finger lifts.

.gesture(
    DragGesture(minimumDistance: 0)
        .onChanged { _ in isHolding = true }
        .onEnded { _ in
            isHolding = false
            stopTimer()
        }
)

Timer — Fire a block of code at a regular interval. Use it to tick the elapsed time while the button is held.

@State var elapsed: Double = 0
@State var timer: Timer?

func startTimer() {
    timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { _ in
        elapsed += 0.01
    }
}

Tracking the best score — Compare the current result to the stored best and update if it's better.

@State var bestTime: Double = 0

func stopTimer() {
    timer?.invalidate()
    if elapsed > bestTime { bestTime = elapsed }
    elapsed = 0
}

Timer lifecycle

Timers need to be started and stopped explicitly. A running timer that never gets invalidated is a common source of bugs. Notice how stopTimer() always invalidates before doing anything else.

Download and run it

Open the Playgrounds file from GitHub, hit Run, and hold on.

← All apps in this book