调用 reloadData 时 didDeselectItemAtIndexPath 不起作用

didDeselectItemAtIndexPath is not working when reloadData is called

didDeselect当我尝试 select 时,ItemAtIndexPath 方法没有触发。如果我的代码中有任何设置错误,请告诉我。

如果图像被 select 编辑,我试图显示打勾的图标,如果图像被删除 select 则图像消失。

感谢您的帮助。

    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)
}
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
}

我在不重新加载数据的情况下让它工作。只需在 didSelectItemAtIndexPath 和 didDeselectItemAtIndexPath 方法中设置隐藏的 imageTicked。谢谢

试试这个

使用cell.userInteractionEnabled=是;在 cellForRowAtIndexPath 方法中。