更新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
答
您可以实现
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
}
}
感谢您的答复!我更新了代码,但它似乎不起作用。我更新了我的问题。我是否需要在其他地方设置PriorSelectedIndexPath? – winston
好点!我更新了我的答案。 – paulvs
我在你的代码中注意到你在'didSelectItemAtIndexPath'里面放了'PriorSelectedIndexPath'声明,这是错误的,它应该在你的类的顶部声明。 – paulvs