问题
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