1

我有一个水平 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
    }
}

集合视图有多个部分和行。如果我在第一个可见页面中选择一个单元格并滚动,则会在下一个可见页面中选择随机单元格。也就是说,随机单元格在接下来的页面中是红色的。我不希望这样。我想手动选择/更改单元格的颜色。

我怎样才能解决这个问题?

4

3 回答 3

2

不要忘记 UICollectionView 已经嵌入了重用机制,因此您应该直接在单元格类中的“prepareToReuse”方法中取消选择单元格。

于 2019-08-07T08:29:42.723 回答
0

取一个类级别的变量,比如说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-06T16:59:16.463 回答
0

首先,如果你想保留多项选择,你必须记住你在数组中选择的那些,因为如果一个单元格被回收和重用,它会丢失。为此,请使用 [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

这应该确实有效。让我知道我们是否需要进行调整。

于 2019-08-07T09:01:50.313 回答