-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewController.swift
91 lines (76 loc) · 2.65 KB
/
ViewController.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let tableView : UITableView = {
let table = UITableView()
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return table
}()
private var models = [ToDoListItem]()
override func viewDidLoad() {
super.viewDidLoad()
title = "To Do List"
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.frame = view.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(didTappedAdd))
}
@objc private func didTappedAdd() {
let alert = UIAlertController(title: "New Item", message: "Enter New Item", preferredStyle: .alert)
alert.addTextField(configurationHandler: nil)
alert.addAction(UIAlertAction(title: "Submit", style: .cancel, handler: { [weak self] _ in
guard let field = alert.textFields?.first, let text = field.text, !text.isEmpty else {
return
}
self?.createItem(name: text)
}))
present(alert, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = model.name
return cell
}
func getAllItems() {
do {
models = try context.fetch(ToDoListItem.fetchRequest())
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
// Error
}
}
func createItem(name: String) {
let newItem = ToDoListItem(context: context)
newItem.name = name
newItem.createdAt = Date()
do {
try context.save()
getAllItems()
} catch {
// Error
}
}
func deleteItem(item: ToDoListItem) {
context.delete(item)
do {
try context.save()
} catch {
// Error
}
}
func updateItem(item: ToDoListItem, newName: String) {
item.name = newName
do {
try context.save()
} catch {
// Error
}
}
}