Created
June 10, 2020 17:34
-
-
Save daneden/a18515fa862c0b4c8d2a35e6ba362e3c to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
import Combine | |
struct HMS { | |
var h: Int | |
var m: Int | |
var s: Int | |
} | |
struct ContentView: View { | |
@State var enteredValue = "" | |
@State var seconds = 60 | |
@State var isRunning = false | |
@State var elapsed = 0 | |
var timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect() | |
var body: some View { | |
let hms = sToHMS(self.seconds - self.elapsed) | |
return VStack { | |
Spacer() | |
if !self.isRunning { | |
VStack(alignment: .leading, spacing: 4) { | |
Text("Seconds:") | |
.bold() | |
TextField("Seconds", text: $enteredValue) | |
.onReceive(Just(enteredValue)) { typedValue in | |
if let newValue = Int(typedValue) { | |
self.seconds = newValue | |
} | |
}.onAppear(perform:{self.enteredValue = "\(self.seconds)"}) | |
.font(.system(size: 56, weight: .bold, design: .default)) | |
Text(String(format: "(%01d hours, %01d minutes, %01d seconds)", hms.h, hms.m, hms.s)) | |
} | |
} else { | |
Text(String(format: "%02d:%02d:%02d", hms.h, hms.m, hms.s)) | |
.font(Font.system(size: 72, weight: .bold, design: .default).monospacedDigit()) | |
} | |
Spacer() | |
Spacer() | |
Button(action: self.toggleRunning) { | |
HStack { | |
Text(self.isRunning ? "Stop" : "Start") | |
.font(Font.system(size: 16, weight: .bold, design: .default)) | |
.foregroundColor(self.isRunning ? Color.white : Color.black) | |
.frame(minWidth: 100, maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .center) | |
.padding(.horizontal, 12) | |
.padding(.vertical, 4) | |
.background(Capsule().fill(self.isRunning ? Color.red : Color.orange)) | |
.cornerRadius(8) | |
} | |
} | |
.buttonStyle(PlainButtonStyle()) | |
} | |
.padding() | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.onReceive(self.timer) { time in | |
if(self.isRunning && self.elapsed < self.seconds) { | |
self.elapsed += 1 | |
} | |
}.background(Rectangle().fill(Color.black)).colorScheme(.dark) | |
} | |
func toggleRunning() { | |
if(self.isRunning) { | |
self.elapsed = 0 | |
} | |
self.isRunning.toggle() | |
} | |
func sToHMS(_ s: Int) -> HMS { | |
return HMS(h: s / 3600, m: (s % 3600) / 60, s: (s % 3600) % 60) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment