【问题标题】:CollectionView Cell Moving when Selected选中时 CollectionView 单元格移动
【发布时间】:2016-12-14 21:54:49
【问题描述】:

我有一个 CollectionView 问题,我有 a video 显示下面详述的问题。当我单击一个单元格时,它会以一种奇怪的方式移动。 这是我的代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedFilter = indexPath.row

    if filters[indexPath.row] != "Todo" {
        filteredNews = news.filter { $0.category == filters[indexPath.row] }
    } else {
        filteredNews = news
    }
    tableView.reloadData()
    collectionView.reloadData()

}

我的单元格在移动,(只是最后一个单元格,不知道为什么)。

我认为它可能与 collectionView.reloadData() 有关,但我需要这样做以更新绿色条,当我选择一个单元格时你可以看到 on this Video

我怎样才能让它不动?有人遇到过类似的问题吗?

【问题讨论】:

    标签: ios swift swift3 uicollectionviewcell collectionview


    【解决方案1】:

    我注意到您在 collectionView didSelectItemAt 期间重新加载了一个 tableView。如果该 tableView 是您的 collectionView 的超级视图,那将是您出现这种异常行为的确切原因。

    如果不是,我可以提供 3 个解决方案:

    1. This library 有一个视图控制器子类,可以创建您想要显示的效果。
    2. 手动创建不在 collectionView 内的 UIView/UIImageView,但在 collectionView 的 didSelectItemAt 委托方法期间将其位置更新为但在单元格上可视化 - 这需要一些计算,但您的 collectionView 不需要重新加载。李>
    3. 您可以尝试使用 collectionView 的 reloadItem(at: IndexPath) 方法仅重新加载两个受影响的单元格。

    知道当你重新加载一个表格/集合视图时,它不会改变当前的可见单元格。但是每个单元格中的任何内容都会受到影响。

    【讨论】:

      【解决方案2】:

      终于解决了!我删除了 collectionView.reloadData() 并添加了我的代码以更改 didSelectItemAt 中的颜色,以更改当前选定项和旧选定项(我创建了一个变量以查看哪个是旧选定项)。

      如果有人感兴趣,这是我的代码:

      func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
          let oldSelectedFilter = selectedFilter
          if selectedFilter != indexPath.row {
              let oldIndexPath = IndexPath(item: oldSelectedFilter, section: 0)
              selectedFilter = indexPath.row
      
              if filters[indexPath.row] != "Todo" {
                  filteredNews = news.filter { $0.category == filters[indexPath.row] }
              } else {
                  filteredNews = news
              }
              if let cell = collectionView.cellForItem(at: indexPath) as? FiltersCollectionViewCell {
                  cell.selectedView.backgroundColor = MainColor
              }
              if let cell = collectionView.cellForItem(at: oldIndexPath) as? FiltersCollectionViewCell {
                  cell.selectedView.backgroundColor = UIColor(red:0.31, green:0.33, blue:0.35, alpha:1.0)
              }
      
              tableView.reloadData()
          }
      }
      

      【讨论】: