Creating editable collections
Editing lists has always been possible in SwiftUI but before WWDC 2021 and SwiftUI 3, doing so was very inefficient because SwiftUI did not support binding to collections. Let's use bindings on a collection and discuss how and why it works better now.
Getting ready
Create a new SwiftUI project and name it EditableListsFields
.
How to do it…
Let's create a simple to-do list app with a few editable items. The steps are as follows:
- Add a
TodoItem
struct below theimport
SwiftUI line:
struct TodoItem: Identifiable {
let id = UUID()
var title: String
}
- In our
ContentView
struct, let's add a collection ofTodoItem
instances:
@State private var todos = [
TodoItem(title: "Eat"),
TodoItem(title: "Sleep"),
TodoItem(title: "Code")
]
- Replace the body content with a
List
that displays the collection oftodo
items in aTextField
view, which will allow for editing the...