-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Views.swift
121 lines (99 loc) · 2.63 KB
/
Views.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
115
116
117
118
119
120
121
import Atoms
import SwiftUI
struct TodoStats: View {
@Watch(StatsAtom())
var stats
var body: some View {
VStack(alignment: .leading, spacing: 4) {
stat("Total", "\(stats.total)")
stat("Completed", "\(stats.totalCompleted)")
stat("Uncompleted", "\(stats.totalUncompleted)")
stat("Percent Completed", "\(Int(stats.percentCompleted * 100))%")
}
.padding(.vertical)
}
func stat(_ title: String, _ value: String) -> some View {
HStack {
Text(title) + Text(":")
Spacer()
Text(value)
}
}
}
struct TodoFilters: View {
@WatchState(FilterAtom())
var filter
var body: some View {
Picker("Filter", selection: $filter) {
ForEach(Filter.allCases, id: \.self) { filter in
switch filter {
case .all:
Text("All")
case .completed:
Text("Completed")
case .uncompleted:
Text("Uncompleted")
}
}
}
.padding(.vertical)
#if !os(watchOS)
.pickerStyle(.segmented)
#endif
}
}
struct TodoCreator: View {
@WatchState(TodosAtom())
var todos
@State
var text = ""
var body: some View {
HStack {
TextField("Enter your todo", text: $text)
#if os(iOS) || os(macOS)
.textFieldStyle(.roundedBorder)
#endif
Button("Add") {
addTodo()
}
.disabled(text.isEmpty)
}
.padding(.vertical)
}
func addTodo() {
let todo = Todo(id: UUID(), text: text, isCompleted: false)
todos.append(todo)
text = ""
}
}
struct TodoItem: View {
@WatchState(TodosAtom())
var allTodos
@State
var text: String
@State
var isCompleted: Bool
let todo: Todo
init(todo: Todo) {
self.todo = todo
self._text = State(initialValue: todo.text)
self._isCompleted = State(initialValue: todo.isCompleted)
}
var index: Int {
allTodos.firstIndex { $0.id == todo.id }!
}
var body: some View {
Toggle(isOn: $isCompleted) {
TextField("", text: $text) {
allTodos[index].text = text
}
#if os(iOS) || os(macOS)
.textFieldStyle(.roundedBorder)
#endif
}
.padding(.vertical, 4)
.onChange(of: isCompleted) { isCompleted in
allTodos[index].isCompleted = isCompleted
}
}
}