create a custom workout timer in swift in swift

To create a custom workout timer in Swift, you can utilize the Timer class provided by the Foundation framework. Here's an example code snippet:

main.swift
import UIKit

class ViewController: UIViewController {

    var timer = Timer()
    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func startButtonTapped(_ sender: UIButton) {
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }

    @objc func timerAction() {
        counter += 1
        print("Timer counting: \(counter)")
    }

    @IBAction func stopButtonTapped(_ sender: UIButton) {
        timer.invalidate()
    }
}
625 chars
26 lines

In this example, we have a timer property of type Timer and a counter property of type Int. When the user taps on the start button, we create a new timer using Timer.scheduledTimer() and provide it with the time interval (1.0 second), the target (self), the selector (timerAction()) to call every time the timer fires, and whether or not the timer should repeat (true in this case).

In the timerAction() function, we simply increment the counter property and print out its value.

Finally, when the user taps on the stop button, we call invalidate() on the timer to stop it.

Of course, you can customize this code to suit your needs by adjusting the time interval, the way you update the counter, and what actions you take when the timer finishes.

related categories

gistlibby LogSnag