![](/img/trans.png)
[英]Swift 2 - Fatal Error when `didDeselectItemAtIndexPath` is called
[英]didDeselectItemAtIndexPath is not working when reloadData is called
當我嘗試選擇時,didDeselectItemAtIndexPath方法未觸發。 如果我的代碼中有任何設置錯誤,請告訴我。
我試圖顯示勾選的圖標,如果選擇了圖像,如果取消選擇則消失了圖像。
謝謝您的幫助。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(contentsOfFile: self.getMediaFilePath(self.mediaModels[indexPath.row].pathToMedia))
if self.mediaModels[indexPath.row].isSelected {
cell.imageTicked.hidden = false
cell.selected = true
} else {
cell.imageTicked.hidden = true
cell.selected = false
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
cell.backgroundColor = UIColor.magentaColor()
self.mediaModels[indexPath.row].isSelected = true
cell.selected = true
collectionView.reloadData()
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath){
var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
cell.backgroundColor = UIColor.whiteColor()
self.mediaModels[indexPath.row].isSelected = false
cell.selected = false
collectionView.reloadData()
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellSize = (collectionView.frame.width / 4) - 4
return CGSizeMake(cellSize, cellSize)
}
嘗試這個
使用cell.userInteractionEnabled = YES; 在cellForRowAtIndexPath方法中。
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
var cell : CollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.magentaColor()
self.mediaModels[indexPath.row].isSelected = true
cell.selected = true
cell.imageTicked.hidden = false
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath){
var cell : CollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
self.mediaModels[indexPath.row].isSelected = false
cell.selected = false
cell.imageTicked.hidden = true
}
我無需重新加載數據即可正常工作。 只需將imageTicked設置為隱藏在didSelectItemAtIndexPath和didDeselectItemAtIndexPath方法中即可。 謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.