swiftswiftuilazyvgridlazyhgrid

Building a lazy grid with rows and columns - SwiftUI


I am wanting to create a view in my app which acts basically as a table. I believe a lazy grid is the best way to do this in iOS 14, I'm just not sure what I am doing with them. The sort of table I want to create is pictured below: enter image description here

Each of the rows are based off of an object, Player(), I have and then each one of the numbers in the row are attributes the object has, e.g. player.tries, player.pens etc.

My attempt so far has been to loop through all players in the array homeTeam.players and create a HStack with different text according to the individual value. I am getting stuck then on how I would set each column to be the width I want, such as the Name to be the widest and all others much smaller, but also have the headings above them. My code is below:

let layout = [GridItem(.flexible(maximum: 300))]

LazyVGrid(columns: layout){
    HStack{
        Text("Name")
        Spacer()
        Text("T | C | P | DG")
   }
   ForEach(homeTeam.players){ player in
       HStack(spacing: 0){
           Text("player.playerName")
           Spacer()
           Text("\(player.tries) | \(player.convs) | \(player.pens) | \(player.dgs)")
       }
        .padding()
   }
}

Any help on getting the sizing and all numbers in the correct place would be hugely appreciated!


Solution

  • No need for a grid view..

    Section(header: CustomHeaderView()) {
            VStack(spacing: 0){
                ForEach(items){ item in
                    HStack {
                        Text("Field 1")
                        
                        Divider()
                        
                        Text("Field 2")
                        // etc
                    }
                }
            }
            .padding()
            .background(Rectangle().strokeBorder(Color.black)
        }
    

    You can format each field how you like just make sure the header and items are uniform.. you get the picture.