Skip to content

Instantly share code, notes, and snippets.

@scottfinkelstein
Created July 16, 2020 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottfinkelstein/d565241c9d1d4dca41f26b5f09439357 to your computer and use it in GitHub Desktop.
Save scottfinkelstein/d565241c9d1d4dca41f26b5f09439357 to your computer and use it in GitHub Desktop.
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