首页 > 解决方案 > 使用组合 `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
}

标签: iosswiftcombine

解决方案


推荐阅读