【问题标题】:SwiftUI onDelete List with ToggleSwiftUI onDelete List with Toggle
【发布时间】:2020-11-06 22:50:53
【问题描述】:

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

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 的好主意。

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

Thread 1: Fatal error: Index out of range

我真的很想了解为什么会发生这种情况,但是 XCodes 错误消息并没有真正的帮助。我在这里发布了类似的问题:SwiftUI ForEach with .indices() does not update after onDelete(见评论)和这里:SwiftUI: Index out of range when deleting cells with toggle

我真的希望有人能在这个问题上提供帮助,因为我尝试在互联网上寻找解决方案几天,但建议的解决方案都没有真正适合我。

谢谢,尼科

【问题讨论】:

    标签: list foreach swiftui


    【解决方案1】:

    这里是固定的部分代码(使用 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})
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      相关资源
      最近更新 更多