【发布时间】:2019-12-14 03:07:41
【问题描述】:
我有一个水平 UICollectionView,就像 iOS 中的水平日历一样。 分页已启用但不允许MultipleSelection。
self.allowsMultipleSelection = false
self.isPagingEnabled = true
每页只有 5 个单元格。
let cellSize = CGSize(width: self.view.frame.width / 5 , height: 60)
CollectionView 的高度也是 60。
didSelectItemAt 将背景颜色更改为 .red 并且 didDeselectItem 将其重置为 .white。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if let cell = cell {
cell.backgroundColor = .red
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if let cell = cell {
cell.backgroundColor = .white
}
}
集合视图有多个部分和行。如果我在第一个可见页面中选择一个单元格并滚动,则会在下一个可见页面中选择随机单元格。也就是说,随机单元格在接下来的页面中是红色的。我不希望这样。我想手动选择/更改单元格的颜色。
我该如何解决这个问题?
【问题讨论】:
-
单元格是从回收的单元格中重复使用的,您需要以某种方式保持每个单元格的状态并在 cellForRow 中分配值
-
你能展示你的 cellForRowAt 方法吗?
-
您需要保留您选择的索引并在
cellForRow中相应地呈现它
标签: ios swift uicollectionview uicollectionviewflowlayout