Updating SwiftUI view for every x seconds
With the evolution of SwiftUI, even smaller things in iOS Development became worth re-visiting.
In this article we will update a SwiftUI View for every 1 second using few possible ways.
With Combine — ViewModel:
Just created a View Model with timer and small refresh fresh function which increments index and update date. And now we can use the View Model inside SwiftUI View.
With Just StateObject instance the view refreshes every second. The @State instance is just to show that we can still maintain state of view.
Starting with iOS15, we can use new TimelineView to update view periodically. We get timeline instance having date at which update triggered and rate at which update happening. This helps in refreshing the view for every second. This view shows output as follows:
Apart from achieving the 1 second refresh, the “lower bound must be less than upper bound” condition might be reason behind delay.
With In Place Timer
Here again we just used Combine to publish update for every second.
That’s it !!!
Thanks for Reading…