Deleting Cell From UICollectionView

by sisccr

I have displayed images in UICollectionView. I have drag and drop feature added for the cell for this collectionView. Today, I will be adding functionality to delete the cell from the CollectionView when cross button is tapped.

Screen Shot 2016-08-24 at 10.53.25 AM

So, let’s begin.

The cell of collectionView have custom class called EnterCollectionViewCell

I will start by adding a closure variable called action.

 
   var action: (() -> ())?

Add @IBAction for the button in the EnterCollectionView

 
  class EnterCollectionViewCell: UICollectionViewCell {
    var action: (() -> ())?
    @IBOutlet weak var imgView: UIImageView!
    
    @IBAction func btnDeleteEnterImage(sender: UIButton) {
        action?()
    }
}

We will be assigning this closure to action variable in cellForItemAtIndexPath function.

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = self.enterImageCollectionView.dequeueReusableCellWithReuseIdentifier("EnterCollectionViewCell", forIndexPath: indexPath) as! EnterCollectionViewCell
        cell.imgView.image = enterImages[indexPath.row]
            cell.action = {
                    self.enterImages.removeAtIndex(indexPath.row)
                let indexPath = self.enterImageCollectionView.indexPathForCell(cell)
                self.enterImageCollectionView.deleteItemsAtIndexPaths([indexPath!]) 
            }
            return cell
}
Advertisements