2016-04-03 21 views
0

我有一個水平集合視圖,包含11個單元格時選擇一個單元格的邊界變爲綠色。我遇到的問題是,當我選擇單元格時,它會更改不可見單元格的邊框。UICollectionView didDeselectItemAtIndexPath影響多個單元格,並給出「無」

此外,當我選擇最後的單元格時,應用程序崩潰給出「致命錯誤:意外地發現零,同時展開一個可選值」,指didDeselectItemAtIndexPath

可能是什麼問題?

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return frameArray.count 
    } 

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

     let frameCell = collectionView.dequeueReusableCellWithReuseIdentifier("frameCell", forIndexPath: indexPath) as! FrameViewCell 

     dispatch_async(dispatch_get_main_queue()) { 
      frameCell.imageView.image = UIImage(named: self.frameArray[indexPath.row]) 
     } 

     return frameCell 
    } 

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

     dispatch_async(dispatch_get_main_queue()) { 
      let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as! FrameViewCell 

      frameCell.layer.borderWidth = 2 
      frameCell.layer.borderColor = UIColor.greenColor().CGColor 
      frameCell.imageView.alpha = 1.0 

      self.globalFrameIndex = self.frameArray[indexPath.row] 
      self.framesImageViews(self.globalFrameIndex, image: self.globalImage) 


      print(self.frameArray[indexPath.row]) 
     } 
    } 

    func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { 

     dispatch_async(dispatch_get_main_queue()) { 
      let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as! FrameViewCell 

      frameCell.layer.borderWidth = 1 
      frameCell.layer.borderColor = UIColor.whiteColor().CGColor 
      frameCell.imageView.alpha = 0.5 
     } 

    } 

} 

回答

0

改變你的函數做一些if-讓可選檢查:

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { 

    dispatch_async(dispatch_get_main_queue()) { 
     if let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as? FrameViewCell 
     { 
      frameCell.layer.borderWidth = 1 
      frameCell.layer.borderColor = UIColor.whiteColor().CGColor 
      frameCell.imageView.alpha = 0.5 
     } 
    } 
} 

更多信息可以看出in this related question

+0

謝謝..那個問題解釋了一切 – SNos

+0

看起來像你了! –

+0

是的,謝謝,檢查單元格是否在'cellForItemAtIndexPath'中被選中解決了我的問題 – SNos

相關問題