【问题标题】:Swift - Selecting item in Collection ViewSwift - 在集合视图中选择项目
【发布时间】:2015-05-01 06:09:09
【问题描述】:

我在收藏视图中的选定项目有问题。

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

我的代码如下所示:

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 个单元格。

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

【问题讨论】:

    标签: ios swift collectionview


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢! :) 我会试一试
    • 小提醒:如果你使用的是 swift 1.2,请使用原生 Set 类型而不是 NSSet
    【解决方案2】:

    在您的单元格类中使用 prepare for resue 方法。它会正常工作。

    override func prepareForReuse()
     {
            self.backgroundColor = UIColor.lightGrayColor()
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 2022-01-20
      • 2022-01-19
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多