如何通过单击单元格中的按钮来删除 tableView 中的单元格?使用核心数据
Posted
技术标签:
【中文标题】如何通过单击单元格中的按钮来删除 tableView 中的单元格?使用核心数据【英文标题】:How to delete a cell in tableView by clicking a button in a cell? Using coreData 【发布时间】:2017-01-19 13:48:23 【问题描述】:我创建了一个待办事项列表应用程序。 我使用 tableView 列出任务。我为单元格使用了一个自定义类。在单元格内容视图中,我有一个标签和一个完成按钮。我已经在我的代码中成功实现了完成按钮单击操作。它工作正常。
问题
当我单击完成按钮时,它会删除最后添加的任务。但不是点击的那个。当我重试单击完成按钮时,它不执行任何操作。如何解决此错误
下面添加了GIF,点击链接
实体类 ToDo
导入基础 导入核心数据
public class ToDo: NSManagedObject
public override func awakeFromInsert()
self.created = NSDate()
MainVC
import UIKit
import CoreData
class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate
var controller: NSFetchedResultsController<ToDo>!
@IBOutlet weak var taskTextField: CustomTextField!
@IBOutlet weak var tableView: UITableView!
var toDo: ToDo!
override func viewDidLoad()
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// generateData()
attemptFetch()
// to give view to cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
configureCell(cell: cell, indexPath: indexPath as NSIndexPath)
return cell
// custom function
func configureCell(cell: ItemCell, indexPath: NSIndexPath)
let toDo = controller.object(at: indexPath as IndexPath)
// call the method on the ItemCell
cell.configureCell(toDo: toDo)
// done button click
cell.doneBtn.tag = indexPath.row
cell.doneBtn.addTarget(self, action: #selector(MainVC.donePressed), for: UIControlEvents.touchUpInside)
// when select a cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
// it ensure it have object and atleast one object in there
if let objs = controller.fetchedObjects, objs.count > 0
let task = objs[indexPath.row]
performSegue(withIdentifier: "ItemDetailsVC", sender: task)
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
if segue.identifier == "ItemDetailsVC"
if let destination = segue.destination as? ItemDetailsVC
if let task = sender as? ToDo
destination.taskDetails = task
// count of cells
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
// we check here if any sections then take info of them and count
if let sections = controller.sections
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
return 0
// column count
func numberOfSections(in tableView: UITableView) -> Int
if let sections = controller.sections
return sections.count
return 0
// give height of a cell
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
return 70
// fetching function
func attemptFetch()
// create a fetch request with fetching Entity
let fetchRequest: NSFetchRequest<ToDo> = ToDo.fetchRequest()
// sorting area
let dateSort = NSSortDescriptor(key: "created", ascending: true)
fetchRequest.sortDescriptors = [dateSort]
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = self
self.controller = controller
// actual fetching
do
try controller.performFetch()
catch
let error = error as NSError
print("\(error)")
// when tableView changes this function starts listen for changes and
// it will handle that for you
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
tableView.beginUpdates()
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
tableView.endUpdates()
// this function will listen for when we make change
// insertion, deletion .. etc
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)
switch type
case.insert:
if let indexPath = newIndexPath
tableView.insertRows(at: [indexPath], with: .fade)
break
case.delete:
if let indexPath = indexPath
tableView.deleteRows(at: [indexPath], with: .fade)
break
case.update:
if let indexPath = indexPath
let cell = tableView.cellForRow(at: indexPath)
//update the cell data
configureCell(cell: cell as! ItemCell, indexPath: indexPath as NSIndexPath)
break
case.move:
if let indexPath = indexPath
tableView.deleteRows(at: [indexPath], with: .fade)
if let indexPath = newIndexPath
tableView.insertRows(at: [indexPath], with: .fade)
break
@IBAction func addBtnPressed(_ sender: UIButton)
if taskTextField.text != "" && taskTextField.text != nil
toDo = ToDo(context: context)
if let task = taskTextField.text
toDo.title = task
ad.saveContext()
taskTextField.text = ""
self.tableView.reloadData()
// done button
func donePressed()
if toDo != nil
context.delete(toDo)
ad.saveContext()
func generateData()
let task = ToDo(context: context)
task.title = "alwin"
let task1 = ToDo(context: context)
task1.title = "rambo"
let task2 = ToDo(context: context)
task2.title = "monisha"
let task3 = ToDo(context: context)
task3.title = "wounderlist"
let task4 = ToDo(context: context)
task4.title = "presentation"
let task5 = ToDo(context: context)
task5.title = "roundup"
// to save data
ad.saveContext()
ItemDetailsVC
import UIKit
class ItemDetailsVC: UIViewController
var taskDetails: ToDo?
@IBOutlet weak var detailsLbl: UILabel!
override func viewDidLoad()
super.viewDidLoad()
// to clear the <DreamLIst to < only
if let topItem = self.navigationController?.navigationBar.topItem
topItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
// this is execute when tap on an existing cell
if taskDetails != nil
loadItemData()
func loadItemData()
if let task = taskDetails
detailsLbl.text = task.title
override func viewDidLayoutSubviews()
detailsLbl.sizeToFit()
@IBAction func deletePressed(_ sender: UIBarButtonItem)
if taskDetails != nil
context.delete(taskDetails!)
ad.saveContext()
_ = navigationController?.popViewController(animated: true)
故事板,点击下方链接
项目单元
import UIKit
class ItemCell: UITableViewCell
@IBOutlet weak var taskTitle: UILabel!
@IBOutlet weak var doneBtn: UIButton!
var toDo: ToDo?
func configureCell(toDo: ToDo)
taskTitle.text = toDo.title
【问题讨论】:
是 UITableViewCell 的 UIView 部分吗? 我不明白 显示 itemCell 和完成按钮的代码 好的,我现在在我的问题中添加,在 MainVC 的 func donePressed() 中完成按钮代码 【参考方案1】:OK 目前您正在将完成按钮的选择器设置在其容器(单元格)之外,这通常是一种不好的做法,您正在使用 ToDo 配置单元格,但没有在单元格内分配可选项,据说可以保留对 ToDo 的引用。
在我看来,我会稍微改变一下,以便您首先存储对 ToDo 的引用:
func configureCell(toDo: ToDo)
self.toDo = toDo
taskTitle.text = toDo.title
现在在您的单元格上创建一个协议,然后为单元格配置一个 ToDo 和一个委托,然后在按钮按下时告诉委托人您的按钮被相关的 ToDo 按下...
protocol ToDoCellDelegate: class
func toDoCellButtonPressed(todo: ToDo?)
现在在您的单元格上配置为:
func configureCell(toDo: ToDo, delegate: ToDoCellDelegate)
self.delegate = delegate
self.toDo = toDo
taskTitle.text = toDo.title
并向单元格中的委托添加一个引用:
weak var delegate: ToDoCellDelegate?
现在将您的按钮选择器更改为单元格内的函数
func buttonPressed()
self.delegate?.cellToDoButtonPressed(toDo: toDo)
然后在您的 VC 中,您符合在配置中传递 self 的委托并实现委托:
extension ItemDetailsVC: ToDoCellDelegate
func toDoCellButtonPress(toDo: ToDo?)
if let t = toDo
//tell context to delete todo and remove cell.
【讨论】:
你也可以将cell添加到protocol方法中,然后调用tableView.indexPathForCell:Cell获取要删除的indexpath。 将单元格作为参数传递并不是最好的解决方案(想象一下有一个包含大量数据的单元格,这样基本上会一遍又一遍地传递它并做比需要更多的内存工作),你应该通过而是将 indexPath 作为参数 这不是它的工作原理,当你传递单元格时,你只是传递了对单元格的引用,仍然只有 1 个单元格... 我添加了除了最后两个代码块之外的所有内容。我在哪里添加最后两个代码块 ButtonPressed 应该在单元格中,因此您需要将按钮上的选择器更改为单元格内部,并删除在配置单元格中更改的选择器【参考方案2】:好的,那么你应该在 ItemCell 中为你的按钮创建一个 IBAction 插座,然后创建一个这种形式的协议:
protocol ItemDelegate
func clicked()
class ItemCell: UITableViewViewCell
var delegate : ItemDelegate?
var indexPath: IndexPath?
//call delegate?.clicked() where you have the gesture recogniser
然后在 cellForRowAtIndexPath 中
cell.delegate = self
cell.indexPath = indexPath
然后为你的类实现扩展:
extension MyTableView: ItemDelegate
func clicked(indexPath: IndexPath)
//dismiss cell for indexPath
【讨论】:
以上是关于如何通过单击单元格中的按钮来删除 tableView 中的单元格?使用核心数据的主要内容,如果未能解决你的问题,请参考以下文章