更新CollectionView未选中的单元格?

问题描述:

我有一个CollectionView,允许用户触摸一个单元格,它会更改边框颜色。但是,我一次只想选择一个单元格。如何编辑此代码,以便使用边框颜色更新indexpath处的单元格,并且之前选定的单元格将被重置?更新CollectionView未选中的单元格?

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

     self.user["avatar"] = self.avatars[indexPath.row] 

     do { 
      try self.user.save() 
     } catch { 
      print(error) 
     } 

     let cell = collectionView.cellForItemAtIndexPath(indexPath) as! AvatarViewCell 
     cell.layer.borderWidth = 5.0 
     cell.layer.borderColor = UIColor.purpleColor().CGColor 

谢谢!

UPDATE

 let cell = collectionView.cellForItemAtIndexPath(indexPath) as! AvatarViewCell 
     var previouslySelectedIndexPath: NSIndexPath? 
     if previouslySelectedIndexPath != nil { 
      let previousCell = collectionView.cellForItemAtIndexPath(previouslySelectedIndexPath!) as! AvatarViewCell 
      previousCell.layer.borderWidth = 0 
      previousCell.layer.borderColor = UIColor.whiteColor().CGColor 
     } 

     cell.layer.borderWidth = 5.0 
     cell.layer.borderColor = UIColor.purpleColor().CGColor 

你为什么不有一个实例变量(在类文件的开头添加)每次都存先前选定的单元格

var previouslySelectedIndexPath: NSIndexPath? 

然后一个新的小区被选中时,首先删除先前选定单元格的边框,然后将边框添加到新选单元格

if previouslySelectedIndexPath != nil { 
    let previousCell = collectionView.cellForItemAtIndexPath(previouslySelectedIndexPath!) as! AvatarViewCell 
    previousCell.borderWidth = 0 
} 
let currentCell = collectionView.cellForItemAtIndexPath(indexPath) as! AvatarViewCell 
cell.layer.borderWidth = 5.0 
cell.layer.borderColor = UIColor.purpleColor().CGColor 
previouslySelectedIndexPath = indexPath 
+0

感谢您的答复!我更新了代码,但它似乎不起作用。我更新了我的问题。我是否需要在其他地方设置PriorSelectedIndexPath? – winston

+0

好点!我更新了我的答案。 – paulvs

+0

我在你的代码中注意到你在'didSelectItemAtIndexPath'里面放了'PriorSelectedIndexPath'声明,这是错误的,它应该在你的类的顶部声明。 – paulvs

您可以实现

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) 

下面是一个使用香草UICollectionViewCell一个例子:

// MARK: UICollectionViewDelegate 

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

    if let cell = collectionView.cellForItemAtIndexPath(indexPath) { 
     cell.layer.borderWidth = 5.0 
     cell.layer.borderColor = UIColor.purpleColor().CGColor 
    } 
} 

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { 

    if let cell = collectionView.cellForItemAtIndexPath(indexPath) { 
     cell.layer.borderWidth = 0 
     cell.layer.borderColor = UIColor.whiteColor().CGColor 
    } 
} 
+0

我该如何设置单元格?它必须不同于'collectionView.cellForItemAtIndexPath(indexPath)as! AvatarViewCell'对吗? – winston

+0

我编辑了我的答案,上面包含示例代码。在你的情况,是的,它将'collectionView.cellForItemAtIndexPath(indexPath)as! AvatarViewCell'。 –

+0

这是最好的答案,因为它优雅地使用框架而不添加不必要的状态跟踪。 – Eppilo