Swift 使用按钮从uicollectionviewCell中删除单个核心数据项
我试图使用collectionviewcell中的按钮删除coreData集合的单个元素。因此,单元格有一个标签,上面有获取核心数据的结果。当我按下按钮时,它会删除单元格,使其不再出现。此外,还应删除核心数据单套项目。我以前在协议中使用过,但没有使用核心数据。核心数据是var itemNameSwift 使用按钮从uicollectionviewCell中删除单个核心数据项,swift,core-data,uicollectionview,protocols,uicollectionviewcell,Swift,Core Data,Uicollectionview,Protocols,Uicollectionviewcell,我试图使用collectionviewcell中的按钮删除coreData集合的单个元素。因此,单元格有一个标签,上面有获取核心数据的结果。当我按下按钮时,它会删除单元格,使其不再出现。此外,还应删除核心数据单套项目。我以前在协议中使用过,但没有使用核心数据。核心数据是var itemName class CustomCell: UICollectionViewCell { @objc func delete() { }} class ViewController: UIViewControl
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")
}
}
导入核心数据
func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
让cell=collectionView.dequeueReusableCell(带有reuseidentifier:“cell Identifier name”,for:indexPath)作为!Cellname
cell.YourButtonNamw.tag=indexPath.row
cell.YourButtonNamw.addTarget(self,action:#选择器(删除),for:.touchUpInside)
返回单元
}
@objc func delete(uu发送方:ui按钮){
让itemName1=itemName[sender.tag]
让context=APP_DELEGATE.persistentContainer.viewContext
var albums=[YourTableName]()
let request=NSFetchRequest(entityName:YourTableName)
request.predicate=NSPredicate(格式:“itemName=%@”,itemName1)
做
{
albums=try context.fetch(请求)
用于相册中的实体{
context.delete(实体)
做
{
尝试context.save()
}
将错误捕获为错误?
{
打印(错误!.localizedDescription)
}
}
}
接住{
打印(“无法删除”)
}
}
var albums=[YourTableName]()是核心数据实体吗?请看这个问题。我取得了一些进展,但无法将其从核心数据中删除。