![](/img/trans.png)
[英]iPhone application crashes in didDeselectItemAtIndexPath of UICollectionView
[英]UICollectionView didDeselectItemAtIndexPath effects multiple cells and gives "nil"
I have an horizontal collection view containing 11 cells when selecting a cell its border changes to green. 我遇到的問題是,當我選擇單元格時,它會更改不可見單元格的邊框。
此外,當我選擇最后一個單元格時,應用程序崩潰並給出“致命錯誤:在展開可選值時意外發現 nil”,指的是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
}
}
}
更改您的函數以進行一些 if-let 可選檢查:
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
}
}
}
更多信息可以在這個相關問題中看到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.