【问题标题】:Swift: Using toolbar button to delete multiple cells in a TableViewSwift:使用工具栏按钮删除 TableView 中的多个单元格
【发布时间】:2019-11-09 09:25:41
【问题描述】:

我目前正在使用核心数据开发待办事项应用程序。用户可以将待办事项标记为已完成。现在,我想在工具栏上添加一个按钮,该按钮可以删除单个选项卡上的每个标记的待办事项。我已经将滑动操作配置为一次删除和标记单元格。我无法为这种情况提供任何代码,只是因为我不知道如何实现这一点。下面提供的代码显示了我如何配置删除滑动。也许这有助于提出解决方案。

override func tableView(_ tableView: UITableView,
               trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{

    let deleteAction = UIContextualAction(style: .destructive, title:  "Delete", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in

        //Haptic Feedback
        AudioServicesPlaySystemSound(1519)

        //Animation
        let range = NSMakeRange(0, self.tableView.numberOfSections)
        let sections = NSIndexSet(indexesIn: range)
        self.tableView.reloadSections(sections as IndexSet, with: .fade)

        //Call delete function from CoreDataManager.swift
        let todo = CoreDataManager.shared.getTodoItem(index: indexPath.row)
        CoreDataManager.shared.deleteItems(item2: todo)
        tableView.reloadData()
        success(true)
    })
    deleteAction.image = UIImage(named: "trash1")
    deleteAction.backgroundColor = .red

    return UISwipeActionsConfiguration(actions: [deleteAction])
}

【问题讨论】:

  • 你如何保留对every marked todo的引用
  • 如果一个待办事项被标签,它将被标记为已完成。此信息存储在核心数据中。我的想法是这样的:if (todo.completed = true){.....}

标签: swift uitableview button cell uitoolbar


【解决方案1】:

您应该通过检查completed = true 并迭代每个todo 并调用CoreDataManager.shared.deleteItems(item2: todo) 来从核心数据中获取所有待办事项

guard let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext else {
    return
}

do {
    let fetchRequest : NSFetchRequest<Todo> = Todo.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "completed == 1")
    let fetchedResults = try context.fetch(fetchRequest) as? [NSManagedObject]
    fetchedResults.forEach { context.delete($0) }
    try context.save()
}
catch {
    print("Error with request: \(error)")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多