Select Multiple Items in SwiftUI List

前端 未结 6 923
遥遥无期
遥遥无期 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:36

    Here is an alternate way that uses a helper I created called Multiselect:

    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)")
                Multiselect(items: $fruits) { fruit in
                    HStack {
                        Text(fruit.name)
                        Spacer()
                        if fruit.isSelected {
                            Image(systemName: "checkmark")
                        }
                    }
                }
            }
        }
    }
    

    With the supporting code here:

    protocol Selectable: Identifiable {
        var name: String { get }
        var isSelected: Bool { get set }
    }
    
    struct Multiselect: View {
        @Binding var items: [T]
        var rowBuilder: (T) -> V
    
        var body: some View {
            List(items) { item in
                Button(action: { self.items.toggleSelected(item) }) {
                    self.rowBuilder(item)
                }
            }
        }
    }
    
    extension Array where Element: Selectable {
        mutating func toggleSelected(_ item: Element) {
            if let index = firstIndex(where: { $0.id == item.id }) {
                var mutable = item
                mutable.isSelected.toggle()
                self[index] = mutable
            }
        }
    }
    

提交回复
热议问题