How does one enable selections in SwiftUI's List

前端 未结 3 564
北荒
北荒 2020-12-05 14:11

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

3条回答
  •  萌比男神i
    2020-12-05 14:30

    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)"))
            }
        }
    }
    

提交回复
热议问题