我有一个CollectionView,允许用户触摸单元格,它将改变边框颜色。但是,我只希望一次选择一个单元格。如何编辑此代码,以便使用边框颜色更新indexpath处的单元格并重置先前选定的单元格?
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
谢谢!
更新
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
答案 0 :(得分:1)
为什么没有实例变量(在类文件的开头添加)来存储先前选择的单元格
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
答案 1 :(得分:1)
您可以实施
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath)
以下是使用vanilla 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
}
}