SwiftUI 列表导航视图 onDelete 警告确认有丑陋的动画。

5

问题在于,每当您将列表放入NavigationView中时,列表行的删除取消动画不太好看。我在body属性中做错了什么吗?

var body: some View {
    NavigationView {
        VStack {
            List {
                ForEach(self.contacts){ contact in
                    ContactRow(contact: contact)
                }.onDelete { self.setDeletIndex(at: $0) }
            }
            .alert(isPresented: $showConfirm) {
                Alert(title: Text("Delete"), message: Text("Sure?"),
                      primaryButton: .cancel(),
                      secondaryButton: .destructive(Text("Delete")) {
                        
                        self.delete()
                      })
            }
            .listStyle(PlainListStyle())
            .navigationTitle("Contacts")
            .navigationBarItems(trailing: HStack {
                Button("Add", action: self.addItem)
            })
        }
    }
}

enter image description here

1个回答

1
一个晚回复,但可能会帮助未来的人们。
这个解决方案需要 iOS 15.0 及以上版本,并且您的“联系人”模型要符合“可哈希”的要求。
我们可以通过停止使用“onDelete”方法并改用“swipeActions”来摆脱这种奇怪的动画效果。我们可以按照以下方式实现:
    List {
        ForEach(Array(contacts.enumerated()), id: \.element) {
            index, contact in
            ContactRow(contact: contact)
                .swipeActions {
                    Button(action: {
                        indexToDelete = index
                        showConfirm = true
                    }) {
                        Text("Delete")
                    }
                    .tint(.red)
                }
        }
    }
    .alert(isPresented: $showConfirm) {
        Alert(
            title: Text("Delete"),
            message: Text("Sure?"),
            primaryButton: .cancel(),
            secondaryButton: .destructive(Text("Delete")) {
                self.delete()
            }
        )
    }

问题的主要原因是.destructive按钮的作用。不需要避免使用.onDelete修饰符。 - zslavman
如果你用NavigationStack而不是NavigationView来包裹内容,这个问题也会发生。 - zslavman
我没有机会看一眼,但是如果这个答案是错误或者误导的话,请随意提交修改 :) - emrepun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接