How does one enable selections in SwiftUI's List

前端 未结 3 566
北荒
北荒 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条回答
  •  爱一瞬间的悲伤
    2020-12-05 14:55

    Rather than using edit mode, I’d just update the row on the basis of the model, and toggle a boolean in the model when the row is tapped as suggested by https://stackoverflow.com/a/57023746/1271826. Perhaps something like:

    struct MultipleSelectionRow: View {
        var content: Binding
    
        var body: some View {
            Button(action: {
                self.content.value.isSelected.toggle()
            }) {
                HStack {
                    Text(content.value.text)
                    Spacer()
                    Image(systemName: content.value.isSelected ? "checkmark.circle.fill" : "circle")
                }
            }
        }
    }
    

    Where

    protocol SelectableRow {
        var text: String { get }
        var isSelected: Bool { get set }
    }
    

    Then you can do things like:

    struct Person: Hashable, Identifiable, SelectableRow {
        let id = UUID().uuidString
        let text: String
        var isSelected: Bool = false
    }
    
    struct ContentView : View {
        @State var people: [Person] = [
            Person(text: "Mo"),
            Person(text: "Larry"),
            Person(text: "Curly")
        ]
    
        var body: some View {
            List {
                ForEach($people.identified(by: \.id)) { person in
                    MultipleSelectionRow(content: person)
                }
            }
        }
    }
    

    Yielding:

提交回复
热议问题