swift - 使用按钮从 uicollectionviewCell 中删除单个核心数据项
问题描述
我正在尝试使用 collectionviewcell 中的按钮删除 coreData 集中的单个元素。所以单元格有一个带有核心数据获取结果的标签。当我点击按钮时,它应该删除使其不再出现的单元格。还应删除核心数据单集项。我以前在协议中使用过这个场景,但没有使用核心数据。核心数据是 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")
}
}
推荐阅读
- vba - 如果 Visible 设置为 False,MS Access Web 浏览器控件不会在 VBA 中加载 HTML 内容
- arduino - 上传任何类型的文件时出现 Arduino ESP32 错误
- scala - 控制台 log4j2 kafka:找不到记录器的附加程序(kafka.utils.Log4jControllerRegistration$)
- reactjs - 为 JWT 使用过滤器时,HttpServletRequest 为空,标头适用于邮递员,但不适用于 localhost
- python - 在 python 中仅使用 numpy 和 scipy 编码 Isomap (& MDS) 函数
- visual-studio-2017 - Visual Studio 2017 中的结构绑定
- reactjs - 设置材质 ui 自动完成的 TextField 子项的样式
- netsuite - 如何在 NetSuite 保存的搜索中使用分组和聚合?
- javascript - 卸载时清除 this.setState 任务的优雅方法,没有 this.mounted 模式?
- macos - 如何在文件添加到文件夹时重命名文件?