delete Single Core Data Item from a uicollectionviewCell using a button

筅森魡賤 提交于 2020-07-23 07:39:19

问题


I am trying to delete a single element of the coreData set using a button inside a collectionviewcell. So the cell has a label with the result of the core data fetch. When I hit the button it should delete the cell making it no longer appear. Also the the core data single set item should be perementley deleted. I have scence this used before in protocols but not using core data.The core data is var itemName.

class CustomCell: UICollectionViewCell {
 @objc func delete() {
}}
class ViewController: UIViewController {
    var itemName : [Item] = []
}

回答1:


In My Case Working 100% Try This

import CoreData 


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell Identifier name ", for: indexPath) as! Cellname
    cell.YourButtonNamw.tag = indexPath.row
    cell.YourButtonNamw.addTarget(self, action: #selector(delete), for: .touchUpInside)
     return cell
    }

     @objc func delete(_ sender:UIButton){
      let itemName1 = itemName[sender.tag]
     let context = APP_DELEGATE.persistentContainer.viewContext
            var albums = [YourTableName]()
            let request = NSFetchRequest<YourTableName>(entityName: YourTableName)
            request.predicate = NSPredicate(format: "itemName = %@" , itemName1)
            do
            {
                albums = try context.fetch(request)

                for entity in albums {
                    context.delete(entity)
                    do
                    {
                        try context.save()

                    }
                    catch let error as Error?
                    {
                        print(error!.localizedDescription)

                    }
                }

            }
            catch _ {
                print("Could not delete")

            }

    }


来源:https://stackoverflow.com/questions/58293724/delete-single-core-data-item-from-a-uicollectionviewcell-using-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!