I tried to make a timer on SwiftUI, which worked just fine:
import SwiftUI
import Combine
struct ContentView: View {
let currentTimePublisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default)
.autoconnect()
@State private var currentTime = Date()
var body: some View {
VStack{
Text("Time is:")
Text("\(currentTime)")
}.onReceive(currentTimePublisher) { (date) in
self.currentTime = date
}
}
}
However, I tried to put the VStack in anything scrollable, be List, or ScrollView, I was not updating when I was scrolling the screen. It worked just fine when I didn't scroll.
I also put the TimerPublisher on the main thread as you can see, but that didn't change anything.
How can I make the SwiftUI update the time while I'm scrolling/interacting?
The scroll view runs the run loop in a different mode (not .default
) while tracking touches. Use mode .common
instead of mode .default
to schedule the timer in the “common” run loop modes, which includes the scroll-tracking mode:
let currentTimePublisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .common)
.autoconnect()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With