ios - Swift - 在 Collection View 中选择项目

标签 ios swift collectionview

我在使用 Collection View 中的选定项时遇到问题。

选中的项目将 backgroundColor 更改为蓝色,但似乎可重复使用的单元格也受到了影响。

我的代码是这样的:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
  var cell = collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCell?
  cell?.contentView.backgroundColor = UIColor.blueColor()

func collectionView(collectionView: UICollectionView, didDeslectItemAtIndexPath indexPath: NSIndexPath) {
  var cell = collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCell?
  cell?.contentView.backgroundColor = UIColor.blackColor()
}

func collectionView(collectionView: UIControllerView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  let cell: boxCell = collectionView.dequeueReusableCellWithReuseIdentifier("demoCell", forIndexPath: indexPath) as boxCell

  cell.cellTitle.text = name[indexPath.row]
}

当我运行应用程序时,选择有效,选择另一个单元格,取消选择其他选定的单元格,但是当我滚动时,可重复使用的单元格也变成蓝色。

我使用的是水平滚动方向,每行只有 1 行和 4 个单元格。

我哪里错了?还有其他人遇到过这个问题吗?

最佳答案

这是正常行为 - 原因是项目被重复使用,并且在重复使用后它们会通过 cellForItemAtIndexPath ,您没有设置背景颜色,因此它们会保留您设置的最后一个 - 在你的案例 didSelect 方法。

您应该创建一个 NSSet,您将在其中保留所有选定的 NSIndexPath,并在选择/取消选择时向其添加/删除 NSIndexPath

设置背景颜色逻辑应该在 cellForItemAtIndexPath 中完成 - 在您检查 NSIndexPath 是否存在于您的 NSSet 中之后,您可以设置所需的颜色。

在选择时,您还必须重新加载特定元素,因此它会为您单击的元素调用 cellForItemAtIndexPath

关于ios - Swift - 在 Collection View 中选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28783557/

相关文章:

ios - Swift iOS 和 Java Sockets 之间的 TCP 通信

swift - "Jumping"到键盘上的数字?

javascript - 正确使用 Backbone.js 和 Marionette 对集合进行分组

ios - 如何为 UICollectionView 的第一个元素设置偏移量

xamarin - 如何将可观察集合绑定(bind)到 xamarin 中的 flexlayout?

ios - 获取 GameScene 的所有 child

ios - 使用 http 和 https 移动网络服务

ios - Swift Csv 解析器对双引号的支持

swift - 在 Swift 中显示来自解析的图像

ios - 确定何时将 subview 添加到 tableView