Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi Column TableViews in MacOS using SwiftUI

I have been experimenting a bit with SwiftUI and can’t seem to find any information at all about how to use SwiftUI to create a multi column TableView as in NSTableView. All the examples I have managed to find show a single column of data.

The documentation at Apple even specifies that the SwiftUI List structure is for single column display of rows of data. This is a pretty fundamental data structure for apps on MacOS yet there seems to be zero mention of it anywhere!

Can someone shed some light on this? I presume it just isn’t ready yet but still.

like image 805
Peter Avatar asked Oct 30 '19 00:10

Peter


3 Answers

Update for macOS 12+ (Monterey)

In macOS Monterey, NSTableView can now be wrapped with Table. In addition, Table can support TableColumns with key paths and trailing closures.

struct ContentView: View {
  @State private var characters = StoryCharacter.previewData

  var body: some View {
    Table(characters) {
      TableColumn("🛠") { CharacterIcon($0) }
        .width(20)
      TableColumn("Villain") { Text($0.isVillain ? "Villain" : "Hero") }
        .width(40)
      TableColumn("Name", value: \.name)
      TableColumn("Powers", value: \.powers)
    }
  }
}
like image 169
Pranav Kasetti Avatar answered Nov 01 '22 20:11

Pranav Kasetti


You could create an HStack and then have a divider between two VStacks where you would put your different columns of data. It would look something like this:

List {
    HStack {
        VStack {
            //Column 1 Data
        }
    }
    Divider()
    VStack {
        //Column 2 Data
    }
}

And then just repeat this for however many columns of data are needed.

like image 1
Ben O Avatar answered Nov 01 '22 20:11

Ben O


This is now available starting with macOS 12 through Table.

like image 1
Austin Conlon Avatar answered Nov 01 '22 20:11

Austin Conlon