This repository has been archived by the owner on Nov 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
TableViewControllerDeleteCells.swift
62 lines (49 loc) · 2.13 KB
/
TableViewControllerDeleteCells.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import UIKit
import DATAStack
import CoreData
class TableViewControllerDeleteCells: UITableViewController {
unowned let dataStack: DATAStack
lazy var dataSource: DATASource = {
let request: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
request.sortDescriptors = [
NSSortDescriptor(key: "name", ascending: true),
]
let dataSource = DATASource(tableView: self.tableView, cellIdentifier: CustomTableViewCell.Identifier, fetchRequest: request, mainContext: self.dataStack.mainContext) { cell, item, indexPath in
let cell = cell as! CustomTableViewCell
cell.textLabel?.text = item.value(forKey: "name") as? String ?? ""
}
dataSource.delegate = self
return dataSource
}()
init(dataStack: DATAStack) {
self.dataStack = dataStack
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: CustomTableViewCell.Identifier)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(toggleEdit))
self.tableView.dataSource = self.dataSource
Helper.addNewUser(dataStack: self.dataStack)
}
@objc func toggleEdit() {
self.setEditing(!self.isEditing, animated: true)
}
}
extension TableViewControllerDeleteCells: DATASourceDelegate {
func dataSource(_ dataSource: DATASource, tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool {
return true
}
func dataSource(_ dataSource: DATASource, tableView: UITableView, commitEditingStyle editingStyle: UITableViewCell.EditingStyle, forRowAtIndexPath indexPath: IndexPath) {
switch editingStyle {
case .delete:
let item = self.dataSource.object(indexPath)
dataStack.mainContext.delete(item!)
try! dataStack.mainContext.save()
default: break
}
}
}