从SwiftUI大纲中删除项目

时间:2020-09-19 11:57:31

标签: swiftui swiftui-list

我有一个SwiftUI大纲列表,希望从中删除选定的项目。这是视图(它是Xcode 12.2,Mac OS目标):

struct ContentView: View {
    @State var root: GrimxnTree<String> = GrimxnTree<String>.testTree
    @State var selection = Set<UUID>()

    var body: some View {
        VStack {
            Text("Hello, Tree World!")
            List(root.children, id: \.id, children: \.childrenOrNil, selection: $selection) { e in
                Text(e.payload)
            }
                .onDeleteCommand {
                    print("Delete \(self.selection)")
                    let s = selection
                    root.remove(ids: s)
                    selection = []
                }

        }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

该模型非常简单:

public struct GrimxnTree<Payload> {
    var payload: Payload
    var children: [GrimxnTree<Payload>] = []
    var id = UUID()
    var childrenOrNil: [GrimxnTree<Payload>]? { 
        // This since `List` requires nil for no children, rather than []
        children.count == 0 ? nil : children 
    }
    
    mutating func remove(itemWithID id: UUID) {
        guard id != self.id else {
            fatalError("Can't delete root")
        }
        for i in 0 ..< self.children.count {
            if self.children[i].id == id {
                self.children.remove(at: i)
                return
            } else {
                self.children[i].remove(itemWithID: id)
            }
        }
    }
    mutating func remove(ids: Set<UUID>) {
        for id in ids {
            self.remove(itemWithID: id)
        }
    }            
    // Some static methods to return sample trees...
    static var testTree: GrimxnTree<String> { ... }

}

从菜单中选择“编辑/删除”总是会导致NSOutlineView错误,例如:

OutlineSketch [10597:853525] [常规] NSOutlineView错误消除 子索引 [索引数:4 (在1个范围内),索引:父级0x0(具有3个子级)中的索引((1-4)]。

我显然在做一些愚蠢的事情,但我完全看不到。谁能看到我要去哪里错了?

0 个答案:

没有答案