I am confused about the timer in Swift. Can I set the 'selector' to a function in ContentView: View?
I has searched 1 day and all the method to achieve a timer using @objc
before function. But when I add @objc
before func update()
, then Xcode will report an error for:
@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes
I have searched 1 day and all the method to achieve a timer using @objc before function.
Try this instead
struct ContentView: View {
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@State private var counter = 0
@State private var running = true
func begin() {
}
func pause() {
}
var body: some View {
VStack {
Text("You have used this app")
.font(.largeTitle)
.padding(.bottom)
Text(String(counter) + " s")
.font(.largeTitle)
.foregroundColor(.blue)
.padding(.top)
.onReceive(timer) { _ in
counter += 1
}
}
.padding()
}
}