我有一個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
感謝您的答覆!我更新了代碼,但它似乎不起作用。我更新了我的問題。我是否需要在其他地方設置PriorSelectedIndexPath? – winston
好點!我更新了我的答案。 – paulvs
我在你的代碼中注意到你在'didSelectItemAtIndexPath'裏面放了'PriorSelectedIndexPath'聲明,這是錯誤的,它應該在你的類的頂部聲明。 – paulvs