Created
December 17, 2021 19:02
-
-
Save mps/626273abd9ab73152f1a784c195cb715 to your computer and use it in GitHub Desktop.
A little stopwatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stopwatch: ObservableObject { | |
@Published private var progressTime = 58 | |
var hours: String { | |
let time = progressTime / 3600 | |
return time < 10 ? "0\(time)" : "\(time)" | |
} | |
var minutes: String { | |
let time = (progressTime % 3600) / 60 | |
return time < 10 ? "0\(time)" : "\(time)" | |
} | |
var seconds: String { | |
let time = progressTime % 60 | |
return time < 10 ? "0\(time)" : "\(time)" | |
} | |
var elapsedTime: String { | |
hours + ":" + minutes + ":" + seconds | |
} | |
private var timer: Timer? | |
func start() { | |
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in | |
self.progressTime += 1 | |
}) | |
} | |
func stop() { | |
timer?.invalidate() | |
} | |
} | |
struct ContentView: View { | |
@ObservedObject var stopwatch: Stopwatch = Stopwatch() | |
var body: some View { | |
VStack { | |
Text(stopwatch.elapsedTime) | |
.padding() | |
}.onAppear() { | |
stopwatch.start() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment