Select Multiple Items in SwiftUI List

前端 未结 6 922
遥遥无期
遥遥无期 2021-02-04 11:37

In UIKit you can select multiple rows of a UITableView by using allowsMultipleSelection - can this be done with the List in SwiftUI?

6条回答
  •  执笔经年
    2021-02-04 12:26

    I found an approach using a custom property wrapper that enables the selection to be modified from a child view using a Binding:

    struct Fruit: Selectable {
        let name: String
        var isSelected: Bool
        var id: String { name }
    }
    
    struct FruitList: View {
        @State var fruits = [
            Fruit(name: "Apple", isSelected: true),
            Fruit(name: "Banana", isSelected: false),
            Fruit(name: "Kumquat", isSelected: true),
        ]
    
        var body: some View {
            VStack {
                Text("Number selected: \(fruits.filter { $0.isSelected }.count)")
                BindingList(items: $fruits) {
                    FruitRow(fruit: $0)
                }
            }
        }
    
        struct FruitRow: View {
            @Binding var fruit: Fruit
    
            var body: some View {
                Button(action: { self.fruit.isSelected.toggle() }) {
                    HStack {
                        Text(fruit.isSelected ? "☑" : "☐")
                        Text(fruit.name)
                    }
                }
            }
        }
    }
    

    Here is the source for BindingList

提交回复
热议问题