使用按钮从uicollectionviewCell删除单个核心数据项 [英] delete Single Core Data Item from a uicollectionviewCell using a button

查看:88
本文介绍了使用按钮从uicollectionviewCell删除单个核心数据项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用collectionviewcell内的按钮删除coreData集的单个元素。因此,该单元格具有一个标签,其中包含了提取核心数据的结果。当我按下按钮时,应删除该单元格,使其不再显示。同样,核心数据单个设置项也应被perementley删除。我曾在协议中使用过此方法,但未使用核心数据。核心数据是var itemName。

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] = []
}


推荐答案

以我的情况工作100%
尝试一下

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")

            }

    }

这篇关于使用按钮从uicollectionviewCell删除单个核心数据项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆