滚动后 didDeselectItemAt 不起作用 swift

didDeselectItemAt not working after scrolling swift

我正在用collectionview设计一个菜单标签栏,我想在标签被选中时改变它的颜色。

一切正常,但是当所选项目不再出现在屏幕中时(由于滚出屏幕),didDeselectItemAt 中的函数不再工作。

有什么办法可以解决这个问题吗?下面是代码:

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        if collectionView == self.productMenuCollectionView {
            guard let cell = self.productMenuCollectionView.cellForItem(at: indexPath) as? ProductMenuCollectionViewCell else {
                return
            }
            cell.label.textColor = UIColor.black
        } else {
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if collectionView == self.productMenuCollectionView {
            let cell = self.productMenuCollectionView.cellForItem(at: indexPath) as! ProductMenuCollectionViewCell
            cell.label.textColor = CustomColor.primary
        } else {
            
        }
    }

您观察到此行为是因为单元格被重复使用,因此一个单元格可用于一个索引路径,但是当该索引路径滚出视图并且新的索引路径滚入视图时,同一个单元格对象可能用于其中一个新单元格。每当您 dequeue 一个单元格时,请记住您可能正在重新配置旧单元格!

所以发生的事情是,旧的选定单元格之一移出视图,并重新配置以用于新的索引路径。您的代码当时可能会从该单元格中删除所选颜色,因此当您向上滚动时,颜色消失了。

你应该做的是,在 ProductMenuCollectionViewCell 中,覆盖 isSelected:

override var isSelected: Bool {
    didSet {
        if isSelected {
            self.label.textColor = CustomColor.primary
        } else {
            self.label.textColor = UIColor.black
        }
    }
}

cellForItemAtIndexPath中:

if collectionView.indexPathsForSelectedItems?.contains(indexPath) ?? false {
    cell.isSelected = true
} else {
    cell.isSelected = false
}