Home > Enterprise >  Show view only if items are selected in list using EditButton and multiple selection in SwiftUI
Show view only if items are selected in list using EditButton and multiple selection in SwiftUI

Time:12-12

The following code lets you select multiple items from a list and clear the selection list when a button is tapped. What I would like to be able to do is not show the Deselect All button unless there are items selected in the list or at least when in editing mode.

Is there a way to show a view only if items are selected? Or at least only when in edit mode?

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()
                }
            }
        }
    }
}

CodePudding user response:

Here is a way for you:

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)
        }
    }
}
  • Related