![](/img/trans.png)
[英]How can I delete a list item in SwiftUI from a child view without using onDelete(perform:)?
[英]How to programatically perform .onDelete animation on List in SwiftUI?
我有 2 种方法可以删除列表中的项目
通过点击自定义删除按钮,我如何以编程方式执行带有 UITableView 默认删除动画的 .onDelete?
重要提示:我的意思不仅仅是使用 withAnimation。 我的意思是当行变成红色并折叠时,列表上的行删除的默认动画。
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)
}
}
与动画执行实际上相同,例如
Button {
withAnimation {
self.countries.removeAll { $0 == country } // << here !!
}
} label: {
Text("Delete")
}
在其他动画的情况下,应删除Button
中的隐式withAnimation
并为每个模型值显式使用一个,例如
List {
ForEach(countries, id: \.self) { country in
// other code ...
}
.onDelete(perform: self.deleteItem)
}
.animation(.default, value: countries) // << here !!
您可以尝试类似这种方法的方法, 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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.