我试图在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更新时间?
let currentTimePublisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .common)
.autoconnect()