我试图在SwiftUI上创建一个计时器,效果很好:
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
}
}
}
但是,我试图将VStack放在任何可滚动的内容中,无论是List还是ScrollView,在滚动屏幕时都没有更新。当我不滚动时,效果很好。
如您所见,我还将TimerPublisher放置在主线程上,但这没有任何改变。
在滚动/交互时如何使SwiftUI更新时间?
答案 0 :(得分:9)
滚动视图在跟踪触摸时以另一种模式(不是.default
)运行运行循环。使用模式.common
而不是模式.default
将计时器安排为“普通”运行循环模式,其中包括滚动跟踪模式:
let currentTimePublisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .common)
.autoconnect()