I can create a List with an EditButton that supports selecting rows. I can also create a List with an EditButton that supports deleting and moving rows. But I can't seem to create a List that supports selecting, moving, and deleting. Is that possible in SwiftUI?
List with EditButton for selection, delete, and move
I think so, but I'm not sure exactly what you're trying to do.
Here, I copied the code from the documentation for EditButton
, and added some ability to select by tapping the text. (Probably you want to render the selection in a different way, not just green text, but I did that for simplicity.)
struct ContentView: View {
@State private var fruits = [
"Apple",
"Banana",
"Papaya",
"Mango"
]
@State private var selected = Set<String>()
var body: some View {
NavigationView{
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
.foregroundColor( selected.contains(fruit) ? Color.green : nil )
.onTapGesture { toggleSelected(fruit) }
}
.onDelete { self.deleteFruit(at :$0) }
.onMove { self.moveFruit(from: $0, to: $1) }
}
.navigationTitle("Fruits")
.toolbar { EditButton() }
}
}
func toggleSelected(_ fruit: String) {
if selected.contains(fruit) { selected.remove(fruit) }
else { selected.insert(fruit) }
}
func deleteFruit(at: IndexSet) { fruits.remove(atOffsets: at) }
func moveFruit(from: IndexSet, to: Int) { fruits.move(fromOffsets: from, toOffset: to) }
}