【问题标题】:Last cell is highlighted when selecting first cell in UICollectionView在 UICollectionView 中选择第一个单元格时突出显示最后一个单元格
【发布时间】:2018-11-25 18:32:48
【问题描述】:

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

这是我用来选择和取消选择单元格的代码?

 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)
    }

【问题讨论】:

  • 集合视图单元格被重复使用。

标签: ios uicollectionview swift4 uicollectionviewcell


【解决方案1】:

我在 S.O. 上找到了这个 link。这很有帮助。为了解决这个问题,我简单地将以下代码添加到我的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

    }

【讨论】:

  • 在集合视图准备单元格时,不需要检查是否选择了单元格。如果您使用的是自定义单元格,prepareForReuse() 是重置边框的更好位置。否则,只需在将可重用单元格出列时初始化为零,然后让选择逻辑工作。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多