Skip to content

Instantly share code, notes, and snippets.

@donguri9
Last active July 28, 2020 21:17
Show Gist options
  • Save donguri9/f4eceb6442fabe532ddd0d3d56410086 to your computer and use it in GitHub Desktop.
Save donguri9/f4eceb6442fabe532ddd0d3d56410086 to your computer and use it in GitHub Desktop.
Stop Watch
import SwiftUI
struct ContentView: View {
@ObservedObject var stopWatchManeger = StopWatchManeger()
var body: some View {
VStack {
Text(String(format:"%.1f",stopWatchManeger.secondsElapsed))
.font(.custom("Futura", size: 50))
.padding(.top,200)
.padding(.bottom,100)
.padding(.trailing,100)
.padding(.leading,100)
if stopWatchManeger.mode == .stop{
Button(action: {self.stopWatchManeger.start()}){
ExtractedView(label: "Start", buttonColor: .yellow, textColor: .black)
}
}
if stopWatchManeger.mode == .start{
Button(action: {self.stopWatchManeger.pause()}){
ExtractedView(label: "Pause", buttonColor: .yellow, textColor: .black)
}
}
if stopWatchManeger.mode == .pause{
Button(action: {self.stopWatchManeger.start()}){
ExtractedView(label: "Start", buttonColor: .yellow, textColor: .black)
}
Button(action: {self.stopWatchManeger.stop()}){
ExtractedView(label: "Stop", buttonColor: .red, textColor: .black)
}
.padding(.top,10)
}
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ExtractedView: View {
var label:String
var buttonColor:Color
var textColor:Color
var body: some View {
Text(label)
.foregroundColor(textColor)
.padding(.vertical,20)
.padding(.horizontal,90)
.background(buttonColor)
.cornerRadius(10)
}
}
class StopWatchManeger:ObservableObject{
enum stopWatchMode{
case start
case stop
case pause
}
@Published var mode:stopWatchMode = .stop
@Published var secondsElapsed = 0.0
var timer = Timer()
func start(){
mode = .start
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){ timer in
self.secondsElapsed += 0.1
}
}
func stop(){
timer.invalidate()
secondsElapsed = 0
mode = .stop
}
func pause(){
timer.invalidate()
mode = .pause
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment