【问题标题】:didDeselectItemAt not working after scrolling swift快速滚动后 didDeselectItemAt 不起作用
【发布时间】:2020-10-05 15:35:19
【问题描述】:

我正在设计一个带有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 {
            
        }
    }

【问题讨论】:

  • 更可靠的方法是将isSelected状态保存在数据模型中并重新加载行。

标签: swift uicollectionview


【解决方案1】:

您正在观察这种行为,因为单元格被重复使用,因此一个单元格可用于一个索引路径,但是当该索引路径滚动到视图之外,而新的索引路径滚动到视图中时,可以使用相同的单元格对象对于其中一个新细胞。每当您 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
}

【讨论】:

  • 但是我可以知道如何设置默认选中项吗?我试过 self.productMenuCollectionView.selectItem(at: IndexPath(index: 0), animated: true, scrollPosition: []) 但它不起作用
  • 您似乎使用了错误的IndexPath 初始化程序。如果要选择第一部分中的第一项,请执行IndexPath(item: 0, section: 0)。这有点超出了这个问题的范围,所以如果这不起作用,我建议你发布另一个问题。 @柏林
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
相关资源
最近更新 更多