【问题标题】:Timer.TimerPublisher doesn’t fire while scrollingTimer.TimerPublisher 在滚动时不会触发
【发布时间】:2019-10-08 14:58:46
【问题描述】:

我尝试在 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 在我滚动/交互时更新时间?

【问题讨论】:

  • 请向我们展示您的非工作代码

标签: ios swift swiftui combine


【解决方案1】:

滚动视图在跟踪触摸时以不同的模式(不是.default)运行运行循环。使用模式.common 而不是模式.default 将计时器安排在“常见”运行循环模式中,其中包括滚动跟踪模式:

let currentTimePublisher  = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .common)
    .autoconnect()

【讨论】:

  • 请注意,.receive(on: ) 向下调用流可能不会通过计时器,因为它会覆盖模式。因此,例如,如果你有这个,你仍然不会收到事件:Timer.publish(every: 1, on: .main, in: .common).autoconnect().receive(on: RunLoop.main)
  • 在我的情况下,事实证明,我不仅需要更改 .common 而不是 .default 模式 - 而且我还需要更改 DispatchQueue.main 而不是 @987654330 @ 在接收订阅中。
猜你喜欢
  • 2011-05-04
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
相关资源
最近更新 更多