Home > Mobile >  Sorting a Table with @FetchRequest's sort descriptors on macOS
Sorting a Table with @FetchRequest's sort descriptors on macOS

Time:01-11

At WWDC21 Apple introduced the Table container, which allows the creation of multi-column tables on macOS using SwiftUI:

enter image description here

We can provide a binding to an array of sort descriptors to make the columns of a table sortable. Here I'm using my @FetchRequest's sortDescriptors for that:

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: [SortDescriptor(\.addDate, order: .reverse)], animation: .default)
    private var videos: FetchedResults<Video>

    @State
    private var selection = Set<Video.ID>()

    var body: some View {
        NavigationView {
            Table(videos, selection: $selection, sortOrder: $videos.sortDescriptors) { // <-- HERE
                TableColumn("Title") {
                    Text($0.title)
                }

                TableColumn("Added") {
                    Text($0.addDate)
                }.width(120)

                TableColumn("Published") {
                    Text($0.publishedAt)
                }.width(120)

                TableColumn("Duration") {
                    Text($0.duration)
                }.width(50)
            }
        }
    }

}

While this compiles and runs without errors, the sorting does not work. I can click on any columns of the table, but nothing happens.

Am I missing something, or is this a known bug with Table on macOS?

CodePudding user response:

Your TableColumn initializers need to be given a value argument, which takes a keyPath that determines how it can be sorted. The example given in the docs:

TableColumn("Given Name", value: \.givenName) { person in
    Text(person.givenName)
}

and where the Text in the view is using the same key path, you can drop the content closure:

TableColumn("Given Name", value: \.givenName)

So in your case, you ought to be able to do something like

TableColumn("Title", value: \.title)

…and so on.

  •  Tags:  
  • Related