ios - 列表滚动后计时器中断
问题描述
我有一个带计时器的课程(每毫秒更新一次)。
class TimeCount {
let currentTimePublisher = Timer.TimerPublisher(interval: 0.001, runLoop: .main, mode: .common)
let cancellable: AnyCancellable?
init() {
self.cancellable = currentTimePublisher.connect() as? AnyCancellable
}
deinit {
self.cancellable?.cancel()
}
}
我还有一个 TimerView 对象的 List()
List() {
ForEach(self.timers) { timer in
TimerPlusView(timer: timer)
}
}
在每个对象内部,我都有一个 Text 可以更新其内容并监听计时器
Text("\(currentTime.timeIntervalSince(timer.time ?? Date()))")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.black)
.opacity(0.5)
.onReceive(timeCount.currentTimePublisher) { newCurrentTime in
self.currentTime = newCurrentTime
}
事情是,在(不是同时)滚动列表大约 100px 之后,计时器停止工作并且标签停止更新,我不知道为什么。
UPD:这是完整项目的链接以供参考。 https://www.dropbox.com/s/47zoizfqp6upz1e/TimerMinimal.zip?dl=0
解决方案
I think the problem is a bug in Xcode. Or at least something very undocumented. Or just a mystery.
The issue seems to occur when the views are being re-used from the table view (like the old dequeue-stuff) which then somehow causes the subscription to get lost, and no timer events are published any more.
Nevertheless, I found something like a work-around.
In TimerPlusView.swift
, move the .onReceive
handler to the very bottom of the body view, e.g.
var body: some View {
Button(action: {
self.timer.title = "Tapped"
}) {
VStack(alignment: .leading) {
Text(timer.title ?? "New Timer")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.black)
Text("\(currentTime.timeIntervalSince(timer.time ?? Date()))")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.black)
.opacity(0.5)
// onReceive doesn't seem to work here:
//.onReceive(timeCount.currentTimePublisher) { newCurrentTime in
// self.currentTime = newCurrentTime
// }
}
}
.buttonStyle(BorderlessButtonStyle())
.contextMenu {
Button(action: {
self.context.delete(self.timer)
}) {
Text("Delete")
}
}
// here, onReceive works:
.onReceive(timeCount.currentTimePublisher) { newCurrentTime in
self.currentTime = newCurrentTime
}
}
推荐阅读
- angular - 如何将 HttpRequest 的值直接返回到变量中
- git - 让git在本地忘记文件但在线记住
- python - 如何在水平 Seaborn 条形图上注释文本?
- c# - MvxObservableCollection 不更新 UI
- python - Django 3 ASGI 和 Django 2 + Channels 有什么不同?
- mysql - 存储引擎大小以及行数和列数
- javascript - 在 tsc TypeScript 编译中包含 CSS 文件
- c# - 检查数组内所有元素的条件是否为真
- jquery - 从 azure 发布和接收
- binary - GraphQL 中的二进制