Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update text using timer in SwiftUI

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)
    }
}        
like image 664
PinkeshGjr Avatar asked Jun 08 '19 07:06

PinkeshGjr


People also ask

How do you describe your UI in SwiftUI?

Meanwhile, in SwiftUI, you can very easily describe your UI by breaking it into multiple views, each responsible for their own piece of the picture. You track each state inside of the given view, then when the view is updated, whatever state each piece is in gets reflected in the UI.

What is Apple’s SwiftUI?

At WWDC this year, one of Apple’s biggest announcements wasn’t a particular feature of the new OSes, but rather a new way to write UIs for your apps using Swift. This new framework, named SwiftUI, uses a declaritive syntax to easily define your UI in far fewer lines of code than before.

How to make a countdown timer in Python?

If you want to run some code regularly, perhaps to make a countdown timer or similar, you should use Timer and the onReceive () modifier. For example, this code creates a timer publisher that fires every second, updating a label with the current time:


2 Answers

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()
            }
    }
}
like image 76
jla Avatar answered Sep 22 '22 11:09

jla


i have managed to update text using alert.

i have declared date as State so whenever date is changed using alert text will also get updated.

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

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

    var body: some View {
        Text("\(newDate)")
            .onReceive(timer) {
                self.newDate = Date()
            }
    }
}
like image 31
PinkeshGjr Avatar answered Sep 22 '22 11:09

PinkeshGjr