【问题标题】:Swift UICollectionView updating cell label on click not updating liveSwift UICollectionView 在单击时更新单元格标签而不是实时更新
【发布时间】:2019-03-20 21:55:23
【问题描述】:

一段时间以来,我一直在尝试弄清楚如何实时更新 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】:

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

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

    【讨论】:

    • 当我删除 reloadItems 时,当我选择单元格时,它不会加粗,直到我点击屏幕上的其他位置。这就是为什么我认为我需要以某种方式刷新以显示新设置。它不会变得大胆,我只是在点击单元格后坐下。这就是我的 cellforItemat let list_item = ViewController.brands[indexPath.item] cell.list_item = list_item return cell
    • @flaskpiao 这很奇怪。如果您将此代码放在willSelectItemAt shouldHighlightItemAtIndexPath 中,是否有帮助?
    猜你喜欢
    • 2018-05-02
    • 2019-02-11
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多