使用组合`receive(on:)` 时,UILabel 文本不会更新

时间:2021-06-18 12:42:34

标签: ios swift combine

我有一个集合视图,我正在尝试使用组合来使集合视图中单元格上的 UILabel 保持最新。但是,如果我使用 receive(on: DispatchQueue.main)(或 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
}

0 个答案:

没有答案