请耐心等待,因为我是 swift 编程的新手。
我有一个 myCollectionViewController
,它是 UICollectionViewController
的子类。 MyCollectionViewController
的单元格是 MyCollectionViewCell
的一个类,这是一个自定义的 UICollectionViewCell
。
我想做的是根据用户选择更改 MyCollectionViewCell
的背景,并在用户滚动到 MyCollectionViewController
的其他单元格时保持此选择.我已经尝试了两种方法来做到这一点,但到目前为止都失败了。
第一种方式是在MyCollectionViewController
的didSelectItemAt
方法中编写代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
cell.contentView.backgroundColor = UIColor.red
}
但是,这没有用,单元格颜色没有改变。
我尝试这样做的另一种方法是更改 MyCollectionViewCell
的 isSelected
属性。
override var isSelected: Bool {
// Change what happens when the user selects a cell
didSet {
if self.isSelected {
self.contentView.backgroundColor = Colours.primary
} else {
self.contentView.backgroundColor = Colours.secondary
}
}
}
虽然这有效,但选择并没有持续存在。也就是说,当用户滚动到 collectionView
中的不同单元格然后向后滚动时,选择消失了。
如有任何建议,我们将不胜感激。
最佳答案
不要在 didSelectItemAt
中使用 dequeue,因为它会返回点击的单元格以外的单元格
var allInde = [IndexPath]()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at:indexPath) as! MyCollectionViewCell
cell.contentView.backgroundColor = UIColor.red
if !(allIndex.contains(indexPath)) {
allInde.append(indexPath)
}
}
并在 cellForItem 中检查要显示的索引路径是否在数组中并为其着色
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "id", for: indexPath as IndexPath) as! MyCollectionViewCell
if allIndex.contains(indexPath) {
cell.contentView.backgroundColor = Colours.primary
}
else {
cell.contentView.backgroundColor = Colours.secondary
}
}
//在这里更新代码
关于ios - 持久化 Collection View 单元格选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239584/