seggy seggy - 28 days ago 5
Swift Question

How to delete a Cell from Collection View?

I want to delete cell from

,when user
(Button) to remove cell.

Here is my code:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell

cell.myLabel.text = self.items[indexPath.row]

cell.deleteBtn?.layer.setValue(indexPath.row, forKey: "Cdelete")
cell.deleteBtn?.addTarget(self, action: Selector(("deleteColor:")), for: UIControlEvents.touchUpInside)

cell.backgroundColor = UIColor.cyan // make cell more visible in our example project

return cell

func deleteColor(sender:UIButton) {

let i : Int = (sender.layer.value(forKey: "Cdelete")) as! Int
self.items.remove(at: i)

What i am doing wrong?


set tag for your deletebutton for fetch the current cell/ know the which cell you tapped

cell.deleteBtn?.tag = indexPath.row
cell.deleteBtn?.addTarget(self, action: #selector(yourVCName. deleteColor(_:)), for: .touchUpInside)

and call like

@IBAction func deleteColor(_ sender: UIButton){
   print("Button pressed