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

问题描述 投票:0回答:1

我一直试图弄清楚如何实时更新一个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])}

    }
}

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

Collection View select cell change text example

ios swift uicollectionview reloaddata
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.