Search code examples
swiftuialignmenttableview

How can I display tabular data with SwiftUI on iPhone?


I'm working on an app for my local sports league.

One view will be the current standings, with several fields on each row: Name of team, Games Played, Points, etc. I want the Teams column to be left-aligned, the other columns to be right-aligned.

It seems the best answer is SwiftUI's Table(), but on iPhone, it only displays the first column.

I've tried using an HStack{} with Text():

List {
    ForEach(selectedStats()) { stats in
        HStack {
            Text (stats.name)
            Spacer()
            Text ("\(stats.totalMatches)")
            Text ("\(stats.standingsPoints)")
        }
    }
}

but I'm having difficulty getting the columns to align left or right across multiple lines in the table.

Is there a way to get Tables to work? Or how can I align my columns?

(P. S. I used the tag TableView, because there is no tag specific to Table or SwiftUI-Table. It would be nice if that could be added.)


Solution

  • I kept researching after I posted and came across some stuff by Paul Hudson of Hacking with Swift fame.

    Alignment and alignment guides

    How to create a custom alignment guide

    Based on those two, I came up with this:

    extension HorizontalAlignment {
        enum GP: AlignmentID {
            static func defaultValue(in context: ViewDimensions) -> CGFloat {
                context[.trailing]
            }
        }
        
        static let gp = HorizontalAlignment(GP.self)
    }
    

    and then I apply

    .alignmentGuide(.gp) { d in d[HorizontalAlignment.trailing] }
    

    to each element I want to right-align.

    Seems to do the trick, as well.