I have 2 ways to delete an item in the List
- Swipe. It's achieved by .onDelete modifier and works fine
- Custom Delete button on each List Item.
By tapping on the custom Delete button, how can I programmatically perform the .onDelete with UITableView default deleting animation?
Important: I don't mean just using withAnimation. I mean default animation for row deleting on the List, when row became red and collapsing.
struct ContentView: View {
@State var countries = ["USA", "Canada", "England", "Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
var body: some View {
NavigationView {
List {
ForEach(countries, id: \.self) { country in
HStack {
Text(country)
Spacer()
Button {
//What to put here to trigger default deleting animation?
} label: {
Text("Delete")
}
}
}
.onDelete(perform: self.deleteItem)
}
.navigationBarTitle("Countries", displayMode: .inline)
}
}
private func deleteItem(at indexSet: IndexSet){
self.countries.remove(atOffsets: indexSet)
}
}
CodePudding user response:
Perform actually the same with animation, like
Button {
withAnimation {
self.countries.removeAll { $0 == country } // << here !!
}
} label: {
Text("Delete")
}
in the case of other animations implicit withAnimation
in Button
should be removed and used explicit one per model value, like
List {
ForEach(countries, id: \.self) { country in
// other code ...
}
.onDelete(perform: self.deleteItem)
}
.animation(.default, value: countries) // << here !!
CodePudding user response:
you could try something like this approach to I want default List deleting animation like row became red and collapsing.
:
struct ContentView: View {
@Environment(\.editMode) var editMode // <-- here
@State var countries = ["USA", "Canada", "England", "Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
var body: some View {
NavigationView {
List {
ForEach(countries, id: \.self) { country in
HStack {
Text(country)
Spacer()
Button {
// -- here
editMode?.wrappedValue = .active == editMode?.wrappedValue ? .inactive : .active
} label: {
Text("Delete")
}
}
}
.onDelete(perform: self.deleteItem)
}
.navigationBarTitle("Countries", displayMode: .inline)
// .navigationBarItems(trailing: EditButton()) // <-- here if desired
}
}
private func deleteItem(at indexSet: IndexSet){
self.countries.remove(atOffsets: indexSet)
}
}