gpt4 book ai didi

ios - 更新未选中的 CollectionView 单元格?

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:39 24 4
gpt4 key购买 nike

我有一个 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

谢谢!

更新

       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

关于ios - 更新未选中的 CollectionView 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35685947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com