带切换的SwiftUI onDelete列表 [英] SwiftUI onDelete List with Toggle

查看:211
本文介绍了带切换的SwiftUI onDelete列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我关于这个问题的第三个问题.到目前为止,还没有解决方案没有崩溃.我想在"Toggles"列表上滑动删除.我的(简化)代码如下所示:

This is my third question on this issue. So far there was no solution that didn't crash. I want to swipe-delete on a List with Toggles. My (simplified) code looks like this:

struct Item: Identifiable {
    var id = UUID()
    var isOn: Bool
}
struct ContentView: View {
    @State var items = [Item(isOn: true) , Item(isOn: false), Item(isOn: false)]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(items) {item in
                        Toggle(isOn: self.selectedItem(id: item.id).isOn)
                        {Text("Item")}
                }.onDelete(perform: delete)
            }
        }
    }
    
    func delete(at offsets: IndexSet) {
        self.items.remove(atOffsets: offsets)
    }
    
    func selectedItem(id: UUID) -> Binding<Item> {
        guard let index = self.items.firstIndex(where: {$0.id == id}) else {
            fatalError("Item does not exist")
        }
        return self.$items[index]
    }
    
}

我尝试了不同的解决方案,例如使用.indices.enumerated()并遍历索引. func selectedItem()的解决方案来自 https://troz.net/post/2019/swiftui-data-flow/,这是从item获取Bindable的好主意.

I tried different solutions, e.g. with .indices and .enumerated() and looping over the indices. The solution with the func selectedItem() is from https://troz.net/post/2019/swiftui-data-flow/, which is a nice idea to get a Bindable from item.

如果我尝试滑动删除列表项,我总是会收到此错误:

If I try to swipe-delete the list items, I always get this error:

Thread 1: Fatal error: Index out of range

我真的很想了解为什么会这样,但是XCodes错误消息并没有真正的帮助.我在这里发布了类似的问题:带有.indices()的SwiftUI ForEach确实可以不会在onDelete之后更新(请参见评论),并在此处:

I'd really like to understand why this happens, but XCodes error messages doesn't really help. I posted similar questions here: SwiftUI ForEach with .indices() does not update after onDelete (see comment) and here: SwiftUI: Index out of range when deleting cells with toggle.

我真的希望有人可以解决这个问题,因为我试图在互联网上找到解决方案已有几天,但没有一个建议的解决方案真正为我解决.

I really hope someone can help on this issue, because I try to find a solution on the internet for a few days but none of the suggested solutions really worked out for me.

谢谢Nico

推荐答案

此处是固定的代码部分(已通过Xcode 11.4/iOS 13.4测试)

Here is fixed part of code (tested with Xcode 11.4 / iOS 13.4)

func selectedItem(id: UUID) -> Binding<Item> {
    guard let index = self.items.firstIndex(where: {$0.id == id}) else {
        fatalError("Item does not exist")
    }

    // Don't use direct biding to array element as it is preserved and
    // result in crash, use computable standalone binding instead !!
    return Binding(get: {self.items[index]}, set: {self.items[index] = $0})
}

这篇关于带切换的SwiftUI onDelete列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆