-
Notifications
You must be signed in to change notification settings - Fork 12
/
ToDoViews.swift
114 lines (101 loc) · 3.25 KB
/
ToDoViews.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import SwiftUI
import Combine
struct ToDoList : View {
var toDos: [ToDo]
let onCreateItem: (String) -> Void
let onCheckedClick: (ToDo) -> Void
let onDeleteClick: (ToDo) -> Void
var body: some View {
VStack {
ToDoInput(onCreateItem: onCreateItem)
ScrollView {
LazyVStack {
ForEach(toDos, id: \.id) { toDo in
ToDoItem(
content: toDo.content,
checked: toDo.complete,
onCheckedClick: { onCheckedClick(toDo) },
onDeleteClick: { onDeleteClick(toDo) }
)
}
}
Spacer()
}
}.accentColor(Color(red: 0x37/255.0, green: 0x59/255.0, blue: 0xdf/255.0))
}
}
struct ToDoInput : View {
let onCreateItem: (String) -> Void
@State
var input = ""
var body: some View {
VStack {
HStack {
TextField("Description",text: $input)
.padding()
Button("Create") {
if !input.isEmpty {
onCreateItem(input)
input = ""
}
}.padding()
}
Divider()
}
}
}
struct ToDoItem : View {
let content: String
let checked: Bool
let onCheckedClick: () -> Void
let onDeleteClick: () -> Void
var body: some View {
VStack {
HStack {
Image(systemName: checked ? "checkmark.square.fill" : "square")
.padding()
.foregroundColor(checked ? Color(red: 0x37/255.0, green: 0x5A/255.0, blue: 0x86/255.0) : .primary)
.onTapGesture { onCheckedClick() }
Text(content)
Spacer()
Image(systemName: "xmark")
.padding()
.foregroundColor(.red)
.onTapGesture { onDeleteClick() }
}
Divider()
}
}
}
struct ToDoList_Previews: PreviewProvider {
struct Preview : View {
@State
var toDos = [
ToDo(id: 0, content: "Make a list", complete: true),
ToDo(id: 1, content: "Check it twice", complete: false)
]
var body: some View {
ToDoList(
toDos: toDos,
onCreateItem: { input in
toDos.append(ToDo(id: (toDos.last?.id ?? -1) + 1, content: input, complete: false))
},
onCheckedClick: { toDo in
if let updatedIndex = toDos.firstIndex(where: { $0.id == toDo.id }) {
toDos[updatedIndex] = ToDo(id: toDo.id, content: toDo.content, complete: !toDo.complete)
}
},
onDeleteClick: { toDo in
if let removedIndex = toDos.firstIndex(where: { $0.id == toDo.id }) {
toDos.remove(at: removedIndex)
}
}
)
}
}
static var previews: some View {
return Group {
Preview()
}
}
}