Tutorial
How to use lists with CoreData in SwiftUI
We can use lists to display data. Often, the list item itself only shows some information, while more information is shown in a detail view. In SwiftUI, we can combine lists with Navigation Views to achieve just that.
First, we need some data:
@State var names: [String] = ["Florian", "Isabel", "Nick"]
To display a list we can use the built-in UI component:
List {}
We can pass data to the list. This will list each attendee’s name:
List (names) { name in
Text("\(name)")
}
We can also create a list using a ForEach loop.
List {
ForEach(names, id: \.self) { name in
Text("\(name)")
}
}
When we use ForEach, we can mixin other elements, such as sections that we can use to display a section header:
List {
Section(header: Text("Names")) {
ForEach(names, id: \.self) { name in
Text("\(name)")
}
}
}
We can nest multiple children inside a list:
List {
Section(header: Text("Names")) {
ForEach(names, id: \.self) { name in
Text("\(name)")
}
}
Section {}
Section {}
}
To make list items interactive, we can embed the list in a Navigation View. We can then use Navigation Links to link to a new view when a list item is tapped. This example assumed that we have a DetailView that we pass on the name.
NavigationView {
List {
Section(header: Text("Names")) {
ForEach(names, id: \.self) { name in
NavigationLink(destination: DetailView(name: name)) {
Text("\(name)")
}
}
}
}
}
var body: some View {
NavigationView {
List(selection: $selectKeeper) {
ForEach(personen, id: \.id) { person in
Text("\()")
}
.onDelete(perform: onDelete)
}
.listStyle(GroupedListStyle())
.navigationBarItems(trailing: addButton)
.environment(\.editMode, $editMode)
.navigationBarTitle("Teilnehmer")
}
}
}