UICollectionView didSelectItemAtIndexPath 影响多个单元格 - swift

UICollectionView didSelectItemAtIndexPath effects multiple cells - swift

我是 运行 更新单元格背景颜色的非常简单的代码,但是,不止一个单元格正在更新。

        override func viewDidLoad(){
    super.viewDidLoad()
    // getting images from library
    images = PHAsset.fetchAssetsWithMediaType(.Image, options: nil)

    collectionView.allowsMultipleSelection = false
    var nipName2 = UINib(nibName: "CollectionViewCell", bundle:nil)
    collectionView.registerNib(nipName2, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderCell")
    var nipName = UINib(nibName: "MyViewCell", bundle:nil)
    collectionView.registerNib(nipName, forCellWithReuseIdentifier: "Cell")
 }

 func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
 }

 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
 }

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyViewCell
    cell.frame.size.width = 60
    return cell
 }

 func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{
    switch kind
    {
    case UICollectionElementKindSectionHeader:
        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "HeaderCell", forIndexPath: indexPath) as! CollectionViewCell
        return headerView
    default:
        assert(false, "Unexpected element kind")
    }
 }

 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
 {
    var cell = collectionView.cellForItemAtIndexPath(indexPath)
    cell?.backgroundColor = UIColor.redColor()
 }

我有大约 300 个不同的细胞。我只想更新第三个,但随机更改许多其他单元格的背景。

因此集合和 table 视图具有很强的视图重用概念。这可以带来很大的性能提升,因为它不必同时在内存中保留 [在您的情况下] 300 个单元格。

当您在某些单元格上设置背景颜色时,这些单元格有可能在滚动时重复使用。由于您没有在视图显示时明确设置背景,因此它只会使用当前的背景。

要解决此问题,只需在请求视图时设置颜色即可:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
   // This does not guarantee to be a fresh, new cell, can be reused
   var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyViewCell
   cell.frame.size.width = 60
   // Explicitly set the background color:
   cell.backgroundColor = .whiteColor() // or whatever your default color is
   return cell
}

现在很明显这会导致额外的副作用。假设您将单元格的背景颜色更改为红色并滚动离开。当您回来时,您现在将其设置回白色。也就是说,您需要跟踪选择了哪些单元格(可能通过存储它们的索引)并适当地设置它们的颜色。