ios - 使用组合 `receive(on:)` 时,UILabel 文本不会更新
问题描述
我有一个集合视图,我正在尝试使用组合来使 UILabel 在集合视图中的单元格上保持最新。但是,如果我使用receive(on: DispatchQueue.main)
(or RunLoop.main
) 强制消息出现在 UI 线程上(这是我的理解),那么更新不会发生。如果我删除该行,那么一切正常,但我担心我会在将来尝试从 UI 线程更新标签时遇到问题。
有趣的是,我在另一个页面上有完全相同的设置,而且效果很好。关于为什么这一页不起作用,我找不到任何不同的地方。我是Combine 的新手,所以我很有可能错过了一个可能有人可以指出的基本元素。
这是设置...
import Foundation
import UIKit
class MyViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
var subscriptions = Set<AnyCancellable>()
weak var item: MyCoreDataItem!
func setData(item: MyCoreDataItem) {
self.item = item
self.item.publisher(for: \.myStringProperty)
.receive(on: DispatchQueue.main) // Removing this makes it work
.assign(to: \.text, on: myLabel)
.store(in: &subscriptions)
}
}
在控制器上,我设置了一个可区分的数据源......
let diffableDataSource = UICollectionViewDiffableDataSource<Int, NSManagedObjectID>(collectionView: collectionView) { [weak self] (collectionView, indexPath, objectID) -> UICollectionViewCell? in
guard let item = try? self?.app.persistentContainer.viewContext.existingObject(with: objectID) as? MyCoreDataItem else {
print("Managed object not available")
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyViewCell", for: indexPath) as! MyViewCell
cell.setData(item: item)
return cell
}
解决方案
推荐阅读
- javascript - 图像剪辑中心
- c - 如何理解表达式?
- c# - How to get reference to GameObject without using Find() in C#/Unity?
- javascript - Electron ipcMain / ipcRenderer 交付保证
- ruby-on-rails - Rails - 如何在同一操作中重定向、闪烁错误/通知和下载 csv?
- workbox - 如何从服务工作者向 Workbox 类实例的“消息”事件发送消息?
- typescript - NuxtJS Auth 错误与属性不存在
- c++ - 在 wndproc 和 MSG 中处理窗口消息,有什么区别?
- firebase - 如何使用 vue.js 和 firebase(目录结构)
- javascript - MaterializeCSS 中带有复选框的可折叠标题