2016-12-14 77 views
0

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

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()有关但是我需要这样做来更新绿色条,当我选择一个Cell时可以看到on this Video

我该如何让它不动?有人有类似的问题?

回答

0

终于我解决了!我删除了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() 
    } 
} 
1

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

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

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

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

相关问题