在 cellForRowAtIndexPath 中重新排序 collectionViewCells 的目标

Reordering targets for collectionViewCells in cellForRowAtIndexPath

我正在尝试在我的 collectionViewCell 中实现一个行为。

Cell 检查是否有该单元格的图像。 如果有图像,您将得到一个十字符号(用于删除) 如果没有图像你会得到一个加号(用于添加)

每当您单击加号时,都会触发一个方法,每当单击十字符号时,都会触发另一个方法。

看看我的

cellForRowAtIndexPath {
    if let imageId = imageIds[indexPath.row] as? String {

    if let imageData = imageForId[imageId]{

                collectionCell.collectionViewImage.image = UIImage(data:imageData)
                collectionCell.collectionViewButton.setImage(UIImage(named: "kreuzzeichen.png"), forState: UIControlState.Normal)
                 collectionCell.collectionViewButton!.addTarget(self, action: "showDeleteAlert:", forControlEvents: UIControlEvents.TouchUpInside)
            }

        }
    } else{

        collectionCell.collectionViewButton.setImage(UIImage(named: "pluszeichen.png"), forState: .Normal)
        collectionCell.collectionViewImage.image = nil
        collectionCell.collectionViewButton.removeTarget(self, action: "showDeleteAlert:", forControlEvents: UIControlEvents.TouchUpInside)
        collectionCell.collectionViewButton!.addTarget(self, action: "pickImage", forControlEvents: UIControlEvents.TouchUpInside)

    }

}

但是删除其中一张图片,会使 collectionView 重新排列它的单元格。必要时交换符号,但不会交换目标。

有办法刷新吗?

我已经尝试检查是否:

collectionCell.collectionViewImage.setImage == UIImage(named:"kreuzzeichen.png")

但它不会比较那些,所以我的代码后记不起作用。

Remove the pickImage target too in the if condition

if let imageData = imageForId[imageId]{

         collectionCell.collectionViewImage.image = UIImage(data:imageData)
         collectionCell.collectionViewButton.setImage(UIImage(named: "kreuzzeichen.png"), forState: UIControlState.Normal)
         collectionCell.collectionViewButton!.addTarget(self, action: "showDeleteAlert:", forControlEvents: UIControlEvents.TouchUpInside)
         collectionCell.collectionViewButton.removeTarget(self, action: "pickImage:", forControlEvents: UIControlEvents.TouchUpInside)
    }
     else {
        collectionCell.collectionViewButton.setImage(UIImage(named: "pluszeichen.png"), forState: .Normal)
        collectionCell.collectionViewImage.image = nil
        collectionCell.collectionViewButton.removeTarget(self, action: "showDeleteAlert:", forControlEvents: UIControlEvents.TouchUpInside)
        collectionCell.collectionViewButton!.addTarget(self, action: "pickImage", forControlEvents: UIControlEvents.TouchUpInside)

    }