Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: InsetGroupedListStyle List and full-width header

How to make a full-width header using List with InsetGroupedListStyle on iOS? One way is to use negative padding (as an example in my code), but this doesn't seem like the best solution using fixed value as it may change in the future.

Is there a better way?

Example code:

import SwiftUI

struct ContentView: View {
    var body: some View {
        List {
            Section (header:
                        VStack {
                            Text("Header")
                                .foregroundColor(.white)
                        }
                        .frame( // This doesn't remove list's paddings
                              minWidth: 0,
                              maxWidth: .infinity,
                              minHeight: 0,
                              maxHeight: .infinity,
                              alignment: .topLeading
                            )
                        .background(Color.red)
//                      .padding(.horizontal, -16) // This works, but fixed value is not the best solution.
                        .textCase(nil)
                        .font(.body)
            ) {
            Text("Hello, world!")
                .padding()
            }
        }
        .listStyle(InsetGroupedListStyle())
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
like image 668
mallow Avatar asked Oct 22 '25 08:10

mallow


2 Answers

You could set the width of the header to the width of the screen, and the padding (x2) you need could be reduced from the width. To can achieve this using a GeometryReader. For example,

// Geometry reader to get the width
GeometryReader { reader in
    List {
        Section (header:
            VStack {
                Text("Header")
                    .foregroundColor(.white)
            }
            // Setting the frame of the Header to the size of the screen
            // Reducing 20 from the width, giving a padding of 10 on each side
            .frame(width: reader.size.width - 20, height: 20, alignment: .leading)
            .background(Color.red)
            .textCase(nil)
            .font(.body)
            ) {
                Text("Hello, world!")
                    .padding()
            }
        }
        .listStyle(InsetGroupedListStyle())
}

You can see the result below

enter image description here

like image 121
Visal Rajapakse Avatar answered Oct 23 '25 22:10

Visal Rajapakse


you could try this:

...
{
  Text("Hello, world!").padding()
}.headerProminence(.increased)     // <--- here
like image 29
workingdog support Ukraine Avatar answered Oct 23 '25 23:10

workingdog support Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!