TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Different text alignment in header of LazyVGrid

Forums > SwiftUI

@brllp  

Hi Folks!

I'm working on a rather simple grid layout with sticky headers. It is as follows:


  var columns: [GridItem] {
    [GridItem(.fixed(131)),
     GridItem(.fixed(131)),
     GridItem(.fixed(131))]
  }

  var body: some View {
    ScrollView(.vertical) {
      LazyVGrid(columns: columns, alignment: .center, spacing: 15, pinnedViews: [.sectionHeaders]) {
        ForEach(viewModel.sections, id: \.id) { section in
          Section {
            ForEach(section.elements, id: \.id) { element in
              ElementView(element: element)
            }
          } header: {
            Text("Secion header")
              .background(Color.white)
          }
        }
      }
    }
    .background(Color.gray)
    .navigationTitle("Title")
  }

This results in centering both grid items and text in the section header. Now, this is the part that I don't like: I would like to have text in the section header aligned to the leading edge, ideally with the same content offset as the first item in the row.

I'm scratching my head and I can't achieve such an effect. Can you please recommend so clever way to do this? Maybe I should embed LazyVGrid into List?

1      

@Bnerd  

Hi, what if you place your the content of your header in a Hstack and add a Spacer() to push it to the left(leading)

HStack {
                          Text("Secion header")
                              .background(Color.white)
                          Spacer()
                      }

it ain't pretty but it works :P

1      

@brllp  

Thank you @Bnerd. I tried this already. The problem with that solution is that the header section is then glued into the leading edge, like this:

grid, no bueno

Now, I could do something like this:

                HStack {
                  Text("Section header")
                    .background(Color.white)
                    .padding(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 0))
                  Spacer()
                }

which results in an effect that I aim to achieve:

grid, bueno

but I don't think that's a scalable solution: I'm not sure if setting leading padding to 15 will scale the same on all devices. Hence my doubts on what is the proper way to achieve this.

1      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.