How to update text using timer in SwiftUI

PinkeshGjr picture PinkeshGjr · Jun 8, 2019 · Viewed 8.6k times · Source

I have text in view now i want to update that text using alert on every second.

Here is code i have done.

struct CountDownView : View {
    var body: some View {       
        VStack{
            Text("Update text with timer").lineLimit(nil).padding(20)

            }.navigationBarTitle(Text("WWDC"), displayMode:.automatic)
    }
}        

Answer

jla picture jla · Jul 9, 2019

Using Combine:

struct CurrentDateView : View {
    @State var now = Date()

    let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()

    var body: some View {
        Text("\(now)")
            .onReceive(timer) {
                self.now = Date()
            }
    }
}