Home > Back-end >  How to use Timer in Swift?
How to use Timer in Swift?

Time:11-07

I am confused about the timer in Swift. Can I set the 'selector' to a function in ContentView: View?

enter image description here

I has searched 1 day and all the method to achieve a timer using @objc before function. But when I add @objc before fun update(), the Xcode will report an error for "@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes"

CodePudding user response:

I have searched 1 day and all the method to achieve a timer using @objc before function.

  • for future reference add suffix or tag "swiftui" before any search related to swiftui, so the search engine you are using gives you swiftui related results. It may still have solutions from UIKit or ObjC, but atleast few will give out right result
  • timer was initially written in Objc way before SwiftUI came into picture, which is why you are getting those results.
  • Combine came up with an entirely new Timer publisher method, which can be used here with swiftui. Added an example below

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()
    }
}
  • Related