首页 > 解决方案 > 使用按钮从 uicollectionviewCell 中删除单个核心数据项

问题描述

我正在尝试使用 collectionviewcell 中的按钮删除 coreData 集中的单个元素。所以单元格有一个带有核心数据获取结果的标签。当我点击按钮时,它应该删除使其不再出现的单元格。还应删除核心数据单集项。我以前在协议中使用过这个场景,但没有使用核心数据。核心数据是 var itemName。

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

标签: swiftcore-datauicollectionviewprotocolsuicollectionviewcell

解决方案


在我的情况下工作 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")

            }

    }

推荐阅读