2016-02-28 104 views
1

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

回答

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 
+0

感謝您的答覆!我更新了代碼,但它似乎不起作用。我更新了我的問題。我是否需要在其他地方設置PriorSelectedIndexPath? – winston

+0

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

+0

我在你的代碼中注意到你在'didSelectItemAtIndexPath'裏面放了'PriorSelectedIndexPath'聲明,這是錯誤的,它應該在你的類的頂部聲明。 – paulvs

1

您可以實現

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

相關問題