How to Delete an Item in a Collection View with a Button in the Cell

How do I delete an item in a collection view with a button in the cell?

Closures aren't overcomplicated. Try something like this:

/// the cell
class CollectionCell: UICollectionViewCell {
var deleteThisCell: (() -> Void)?
@IBAction func deletePressed(_ sender: Any) {
deleteThisCell?()
}
}
/// the view controller

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "yourReuseID", for: indexPath) as! CollectionCell
cell.deleteThisCell = { [weak self] in

/// your deletion code here
/// for example:

self?.yourDataSource.remove(at: indexPath.item)

do {
try self?.realm.write {
self?.realm.delete(projects[indexPath.item]) /// or whatever realm array you have
}
self?.collectionView.performBatchUpdates({
self?.collectionView.deleteItems(at: [indexPath])
}, completion: nil)
} catch {
print("Error deleting project from realm: \(error)")
}
}
}

Deleting a cell from UICollectionView when clicking on a button inside the cell

so I managed to fix the issue by doing this:

cell.deleteBtn.rx.controlEvent(.touchDown).subscribe(onNext: {_ in


let point = cell.deleteBtn.convert(CGPoint.zero, to: self.shopsCV)

guard let indexPath = self.shopsCV.indexPathForItem(at: point)
else{return}


self.data = (self.viewModel?.shops.value)!
self.data.remove(at: indexPath.row)
self.viewModel?.shops.accept(self.data)

self.shopsCV.performBatchUpdates({
}){(finished) in

self.shopsCV.reloadItems(at: self.shopsCV.indexPathsForVisibleItems)

}

}).disposed(by: cell.disposeBag)

return cell

I had to use a disposeBag from within the cell in order to prevent it from clicking the delete btn twice or more.
this works fine if the cells are in random and not in order.

How to delete a indiviudal collection view cell via button inside that cell using a tag

You need to delete the item from the dataSource/core data and then reload the collection view.

@objc func elete(_ sender:UIButton){
itemName.remove(at: sender.tag) // this removes from array, but you should also remove from core data.

collectionView.reloadData()
}

How to add a delete button to Collection View Cell in Swift?

Got it working! Here's how:

  1. I added a button to the cell in the Storyboard.
  2. Connected an outlet to the UICollectionViewCell class.
  3. Edited view controller code to:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell

    cell.usernameLabel.text = userNames [indexPath.row]

    cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
    cell.deleteButton?.addTarget(self, action: "deleteUser:", forControlEvents: UIControlEvents.TouchUpInside)

    // Remove the button from the first cell
    if (indexPath.row == 0){
    var close : UIButton = cell.viewWithTag(11) as! UIButton
    close.hidden = true
    }

    return cell
    }

    func deleteUser(sender:UIButton) {

    let i : Int = (sender.layer.valueForKey("index")) as! Int
    userNames.removeAtIndex(i)
    UserSelectCollection.reloadData()
    }

Many thanks to JigarM for his examples on GitHub:
https://github.com/JigarM/UICollectionView-Swift

How delete multiple selected cells from collection view? (swift)


var _selectedCells = [IndexPath]()

Add Cell Index

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if self.EditToolBar.isHidden == true {
self.performSegue(withIdentifier: "DetailVC", sender: indexPath.item)
} else {
print("EditMode")
if !(_selectedCells.contains(indexPath)) {
_selectedCells.add(indexPath)
print("selectedCells - \(_selectedCells)")
}

}
}

Delete cell Index

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if self.EditToolBar.isHidden == true {
} else {
print("EditMode")

if let index = _selectedCells.index(where: { $0 == indexPath }) {
_selectedCells.remove(at: index)
print("unselectedCells - \(_selectedCells)")

}
}
}

Delete Button Action

@IBAction func DeleteButton(_ sender: UIBarButtonItem) {
// Two Things To make sure of
// 1. Never call reloadData() right after insert/move/deleteRows..., the insert/move/delete operation reorders the table and does the animation
// 2. Call insert/move/deleteRows... always after changing the data source array.


// remove the data from data Source Array you passed ,of selected cells you're trying to delete .

self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at indexPaths: _selectedCells)
}){
// optional closure
print(“finished deleting cell”)
}



}

How to do delete button that delete one cell in collection view and row in sqlite in xamarin?

assign a handler for your button

<Button Text="Delete" Clicked="RemovePlane" ... />

in your handler

public void RemovePlane(object sender, EventArgs args)
{
var button = (Button)sender;
var plane = (Airplane)button.BindingContext;

var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane);

// finally, either refresh your ItemsSource from your db
// or if you are using an ObservableCollection just remove
// it from the collection
}


Related Topics



Leave a reply



Submit