繁体   English   中英

Swift UICollectionView点击更新单元格标签不更新实时

[英]Swift UICollectionView updating cell label on click not updating live

我一直试图弄清楚如何实时更新一个uicollectionview。

我尝试使用reloadData,reloadItems和reloadSections来使用许多不同的方法来完成这项工作。 而不是使用DispatchQueue.main.async。

我无法弄清楚如何让用户选择其中一个单元格,以便在用户面前更新该单元格的内容。 特别是根据单元格上的点击使标签文本变为粗体而不是粗体。

这是我在swift中设置的标签:

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = ""
    return label
}()

这是collectionview的didselectitem

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath) as! FilterCollectionViewCell
    let selected = ViewController.brands[indexPath.item]
    if FilterLauncher.selectedOptions.contains(selected){
        let loc = FilterLauncher.selectedOptions.firstIndex(of: selected)
        FilterLauncher.selectedOptions.remove(at: loc!)
        cell.nameLabel.font = UIFont.boldSystemFont(ofSize: 2.0)
        DispatchQueue.main.async {
            collectionView.reloadItems(at: [indexPath])
        }
    }
    else{
        FilterLauncher.selectedOptions.append(selected)
        cell.nameLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
        DispatchQueue.main.async{
             self.collectionView.reloadItems(at: [indexPath])}

    }
}

它最终会将所选单元格的文本更改为粗体,但它会延迟执行。 当我试图选择第一个粗体时,我需要尝试选择另一个单元格。 当我第一次选择单元格时,它会闪烁我想要的更改,但随后又返回。

集合视图选择单元格更改文本示例

我认为你不需要在选择后调用collectionView.reloadItems(at: [indexPath]) 直接访问单元格的标签应该进行更改而无需重新加载单元格。

我的猜测是你在cellForItemAt有一些出列代码, cellForItemAt字体设置为正常,所以当你点击一个单元格时,它的标签会被设置为粗体,但是当你重新加载它时会立即恢复正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM