Select Multiple Items in SwiftUI List

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

    my 2 cents with a super simple solution:

    import SwiftUI
    
    struct ListDemo: View {
        @State var items = ["Pizza", "Spaghetti", "Caviar"]
        @State var selection = Set()
        
        var body: some View {
            List(items, id: \.self, selection: $selection) { (item : String) in
                
                let s = selection.contains(item) ? "√" : " "
                
                HStack {
                    Text(s+item)
                    Spacer()
                }
                .contentShape(Rectangle())
                .onTapGesture {
                    if  selection.contains(item) {
                        selection.remove(item)
                    }
                    else{
                        selection.insert(item)
                    }
                    print(selection)
                }
            }
            .listStyle(GroupedListStyle())
        }
    }
    

    using string in set is sub-optimal, better to use id OR using strict with data and selection state.

提交回复
热议问题