SwiftUI:InsetGroupedListStyle 列表和全角标题

mal*_*low 3 list ios swift swiftui

如何在 iOS 上使用带有 InsetGroupedListStyle 的 List 制作全角标题?一种方法是使用负填充(作为我的代码中的示例),但这似乎不是使用固定值的最佳解决方案,因为它将来可能会发生变化。

有没有更好的办法?

示例代码:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

Vis*_*kse 10

您可以将width标题的宽度设置为width屏幕的宽度,并且可以从宽度中减少所需的填充(x2)。可以使用GeometryReader. 例如,

// 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())
}
Run Code Online (Sandbox Code Playgroud)

你可以看到下面的结果

在此输入图像描述