在 UICollectionView 中选择第一个单元格时突出显示最后一个单元格

Last cell is highlighted when selecting first cell in UICollectionView

我的 UICollectionView 有一个奇怪的问题。当我 select 我的集合视图中的第一个单元格时,最后一个单元格突出显示但未显示在 selected 索引路径数组中。为什么会这样?

这是我用来 select 和 deselect 单元格的代码?

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderWidth = highlightedCellBorderWidth
        cell?.layer.borderColor = UIColor.yellow.cgColor
        selectedImages.append(imageArray[indexPath.item])
        print(selectedImages)
        print(collectionView.indexPathsForSelectedItems)

    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

            let cell = collectionView.cellForItem(at: indexPath)
            cell?.layer.borderWidth = 0
      let index = selectedImages.index(of: imageArray[indexPath.item])
        selectedImages.remove(at: index!)
        print(selectedImages)
          print(collectionView.indexPathsForSelectedItems)
    }

您没有显示您的单元格是如何初始化的,但是...

collectionView(_:didDeselectItemAt:) 仅在用户成功取消选择项目时调用。如果您以编程方式取消选择项目,则不会调用它。如果您在初始化单元格时没有重置图层的 borderWidth,则当单元格被集合视图重用时,非零宽度将继续存在。

我在 S.O 上找到了这个 。这很有帮助。为了解决这个问题,我只是将以下代码添加到我的 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {}.

代码...

 if collectionView.indexPathsForSelectedItems?.contains(indexPath) == true {
        print("This cell is selected \(indexPath.item)")
        cell?.layer.borderWidth = 3
        cell?.layer.borderColor = UIColor.yellow.cgColor
    }else{
        cell?.layer.borderWidth = 0

    }