如何对表格中的子项进行排序?

问题描述 投票:0回答:1

对分层表中的项目进行排序不起作用!

型号

struct File: Decodable {
    /*File name (including relative path)*/
    let name: String
    /*File size (bytes)*/
    let size: Int64    
    var children: [File]?
}

extension File: Identifiable {
    var id: String { name } // unic for node
}

桌子

struct TableView: View {
    
    @Environment(AppContext.self) private var appContext
    @State private var fileTree: [File] = []
    @State private var sortOrder = [KeyPathComparator(\File.name)]
    @State private var selectedFile: Set<String> = Set()
    
    var body: some View {
        Table(fileTree, children: \.children, selection: $selectedFile, sortOrder: $sortOrder) {
            TableColumn("Name", value: \.name) { file in
                ItemName(for: file)
                    .padding(.leading, 5)
            }
            .width(ideal: 300)
            TableColumn("Size", value: \.size) {
                Text($0.size, format: .byteCount(style: .memory, spellsOutZero: false))
                    .frame(maxWidth: .infinity, alignment: .trailing)
            }
            .width(ideal: 50)
        }
        .onChange(of: sortOrder) { _, newValue in
            fileTree.sort(using: newValue)
        }
    }
}

但是,排序仅适用于根元素。我有什么遗漏的吗?

swiftui swiftui-table
1个回答
0
投票

您可能已经知道,

Table
不会为您进行任何排序。排序应该由您完成,在
onChange(of: sortOrder)
中。您正在做
fileTree.sort(using: newValue)
,这当然会对根元素进行排序。

您需要编写自己的排序逻辑来对文件的子文件进行排序。如果你想单独递归地对每个

children
数组进行排序,你可以编写如下扩展:

extension MutableCollection where Self: RandomAccessCollection {
    mutating func recursiveSort<S, Comparator>(
        using comparators: S,
        children: WritableKeyPath<Element, Self?>
    ) where
        S : Sequence,
        Comparator : SortComparator,
        Comparator == S.Element,
        Element == Comparator.Compared
    {
        sort(using: comparators)
        for i in indices {
            self[i][keyPath: children]?.recursiveSort(using: comparators, children: children)
        }
    }
}

用途:

.onChange(of: sortOrder) { _, newValue in
    fileTree.recursiveSort(using: newValue, children: \.children)
}
© www.soinside.com 2019 - 2024. All rights reserved.