SwiftUI: Enabling single/multiple selection in List
To make List selectable, you need to provide a selection variable binding for single selection. Selection binding to a Setcreates a list which provide support for multiple selection. Below is the example to show how to add multiple selection support in List:
struct Book: Identifiable, Hashable {
let name: String
let id = UUID()
}
private var books = [
Book(name: "SwiftUI"),
Book(name: "Swift"),
Book(name: "Objective-C"),
Book(name: "C#"),
Book(name: "Java"),
Book(name: "SwiftUI"),
Book(name: "Swift"),
Book(name: "Objective-C"),
Book(name: "C#"),
Book(name: "Java")
]
struct ContentView: View {
@State private var multiSelection = Set<UUID>()
var body: some View {
NavigationView {
List(books, selection: $multiSelection) {
Text($0.name)
}
.navigationTitle("Books")
.toolbar { EditButton() }
}
Text("\(multiSelection.count) selected")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Note: Good thing here is you have draggable selection of rows :) and you do not need to click on individual row for selection.
To enable only one selection at time you just need to change your selection binding to one UUID selection and you are done :)
@State private var singleSelection: UUID?
How to grab full object in selection instead of just UUID?
To grab selection of object you need to pass id as \.self:
@State private var singleSelection: UUID?@State private var singleSelection: Book?
var body: some View {
NavigationView {
List(books, id: \.self, selection: $singleSelection) {
Text($0.name)
}
.navigationTitle("Books")
.toolbar { EditButton() }
}
To grab multiple selection of objects just turn selection to set :
@State private var booksSelection = Set<Book>()
Join the Swiftable Community to connect with iOS Engineers.