I'm currently developing an application using SwiftUI.
I'm trying to make a timer app and I want to control Timer.publish() method, so I made methods to start and stop the timer.
But I don't know how to declare variables for Timer.publish()
and then the codes don't work...
How could I declare variables for Timer.publish()
?
ContentView.swift (*This code doesn't build)
import SwiftUI
struct ContentView: View {
@State var timer:Timer! //I don't know how to declare here...
@State var counter = 0
var body: some View {
VStack{
HStack{
Text("RUN")
.onTapGesture {
startTimer()
}
Text("STOP")
.onTapGesture {
stopTimer()
}
}
Text(String(counter))
.padding()
}
.onReceive(timer) { _ in
print("onRecieve")
counter += 1
}
}
func stopTimer() {
self.timer.upstream.connect().cancel()
}
func startTimer() {
self.timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
}
}
TimerControlApp.swift
import SwiftUI
@main
struct TimerControlApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Xcode: Version 12.0.1
iOS: 14.0
Life Cycle: SwiftUI App
Timer.TimerPublisher