我有一个水平的UICollectionView,就像iOS中的水平日历。已启用分页,但不启用allowsMultipleSelection。
self.allowsMultipleSelection = false
self.isPagingEnabled = true每页只有5个单元格。
let cellSize = CGSize(width: self.view.frame.width / 5 , height: 60)集合视图的高度也是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
}
}集合视图有多个节和行。如果我在第一个可见页中选择一个单元格并滚动,则在下一个可见页中选择随机单元格。也就是说,随机单元格在下一页中是红色的。我不想这样。我想手动选择/更改单元格的颜色。
我怎么才能解决这个问题?
发布于 2019-08-07 08:29:42
不要忘记UICollectionView有内置的重用机制,因此您应该直接在单元格类中的"prepareToReuse“方法中取消选择单元格。
发布于 2019-08-06 16:59:16
接受一个类级变量,比如index。
var index = -1正如您所说的,不允许多个选择,因此下面的选项将为您完成此工作。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
index = indexPath.item
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if let cell = cell {
cell.backgroundColor = indexPath.item == index ? .red : .white
}
}每当用户点击任何单元格时,我们都保存在index变量中的位置,然后调用reloadData()通知collectionView关于cellForRowAt中的变化,我们检查我们选择的当前单元格是否将颜色设置为红色,否则为白色。
发布于 2019-08-07 09:01:50
首先,如果要保留多重选择,就必须在数组中记住所选的,因为如果单元格被回收和重用,它就会丢失。为此,使用类似于IndexPath类型的东西)。如果一个选定的单元格足够,您可以使用下面代码的非数组版本。
var selectedItems: [IndexPath] = []然后,在细胞的cellForItemAt(:)中重新着色吗?
cell.backgroundColor = selectedItems.contains(indexPath) ? .red : .white您的didSelectItemAt委托函数应该如下所示:
if !selectedItems.contains(indexPath) { selectedItems.append(indexPath)}
collectionView.cellForItem(at: indexPath)?.backgroundColor = .red以及您的didDeselectItemAt委托函数:
if let index = selectedItems.firstIndex(of: indexPath) { selectedItems.remove(at: index) }
collectionView.cellForItem(at: indexPath)?.backgroundColor = .white这应该会有效的。如果我们要做调整,请告诉我。
https://stackoverflow.com/questions/57378128
复制相似问题