代码之家  ›  专栏  ›  技术社区  ›  fs_tigre

仅当使用EditButton和SwiftUI中的多选功能在列表中选择项目时显示视图

  •  0
  • fs_tigre  · 技术社区  · 3 年前

    Deselect All 按钮,除非列表中或至少在编辑模式下选择了项目。

    struct ContentView: View {
        @State private var itemSelection = Set<String>()
    
        let names = [ "Orange", "Apple", "Grape", "Watermelon"]
    
        var body: some View {
            NavigationView {
                VStack{
                    List(names, id: \.self, selection: $itemSelection) { name in
                        Text(name)
                    }
                    .navigationTitle("Item List")
                    .toolbar {
                        EditButton()
                    }
                    
                    Button("Deselect All"){
                        print("Items: \(itemSelection)")
                        itemSelection.removeAll()
                    }
                }
            }
        }
    }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   swiftPunk Alexander    3 年前

    struct ContentView: View {
        
        @State private var itemSelection = Set<String>()
    
        let names = [ "Orange", "Apple", "Grape", "Watermelon"]
    
        var body: some View {
            NavigationView {
                VStack{
                    List(names, id: \.self, selection: $itemSelection) { name in
                        Text(name)
                    }
                    .navigationTitle("Item List")
                    .toolbar {
                        EditButton()
                    }
                    
                    if !itemSelection.isEmpty {
                        
                        Button("Deselect All"){
                            print("Items: \(itemSelection)")
                            itemSelection.removeAll()
                        }
                        .transition(AnyTransition.move(edge: .bottom))
                        
                    }
    
                }
                .animation(.default, value: itemSelection.isEmpty)
            }
        }
    }