Created
July 16, 2020 01:26
-
-
Save scottfinkelstein/d565241c9d1d4dca41f26b5f09439357 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@Environment(\.managedObjectContext) var context | |
@FetchRequest(entity: Todo.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Todo.title, ascending: true)]) var todos: FetchedResults<Todo> | |
@State private var todoString: String = "" | |
var body: some View { | |
VStack { | |
HStack { | |
TextField("Add a Todo", text: $todoString) | |
Button(action: { | |
self.addTodo() | |
}) { | |
Text("Save") | |
} | |
} | |
.padding() | |
List { | |
ForEach(todos, id:\.self) { todo in | |
Text("\(todo.title ?? "")") | |
} | |
} | |
} | |
} | |
func addTodo() { | |
let todo = Todo(context: context) | |
todo.title = todoString | |
todo.dateAded = Date() | |
do { | |
try context.save() | |
DispatchQueue.main.async { | |
self.todoString = "" | |
} | |
}catch { | |
print(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment