I am trying to create a simple multiple selection List with SwiftUI. I am unable to make it work.
List takes a second argument which is a SelectionManager, so I tri
Edit Mode
As mentioned in a previous answer you can add this in edit mode. This means that the user will have to press the edit button at some point to select rows. This is useful if you want to have a view state and an edit state for your list.
var demoData = ["Phil Swanson", "Karen Gibbons", "Grant Kilman", "Wanda Green"]
struct SelectionDemo : View {
@State var selectKeeper = Set()
var body: some View {
NavigationView {
List(demoData, id: \.self, selection: $selectKeeper){ name in
Text(name)
}
.navigationBarItems(trailing: EditButton())
.navigationBarTitle(Text("Selection Demo \(selectKeeper.count)"))
}
}
}
Constant Edit Mode
You can also simply keep edit mode always on. SwiftUI has environment modifiers, that allow you to manually control any environment variables. In this case we wan to control the editMode variable.
var demoData = ["Phil Swanson", "Karen Gibbons", "Grant Kilman", "Wanda Green"]
struct SelectionDemo : View {
@State var selectKeeper = Set()
var body: some View {
NavigationView {
List(demoData, id: \.self, selection: $selectKeeper){ name in
Text(name)
}
// the next line is the modifier
.environment(\.editMode, .constant(EditMode.active))
.navigationBarTitle(Text("Selection Demo \(selectKeeper.count)"))
}
}
}