Remove/change section header background color in SwiftUI List

后端 未结 6 1274
旧巷少年郎
旧巷少年郎 2021-02-12 12:56

With a simple List in SwiftUI, how do I change/remove the standard background color for the section header

struct ContentView : View {
    var body:         


        
6条回答
  •  [愿得一人]
    2021-02-12 13:24

    I tried to use the custom header code above, and unfortunately could not get it to work in beta 6. That led me to the use of a ViewModifier:

    public struct sectionHeader: ViewModifier{
    var backgroundColor:Color
    var foregroundColor:Color
    public func body(content: Content) -> some View {
        content
        .padding(20)
        .frame(width: UIScreen.main.bounds.width, height: 28,alignment:
        .leading)
        .background(backgroundColor)
        .foregroundColor(foregroundColor)
    }}
    

    Which can be added to the sections in your list as follows:

    struct ContentView: View {
    @ObservedObject var service = someService()
    var body: some View {
        NavigationView {
            List{
                ForEach(someService.sections) {section in
                    Section(header: Text(section.title).modifier(sectionHeader(backgroundColor: Color(.systemBlue), foregroundColor: Color(.white)))){
    

    Hope that helps somebody!

提交回复
热议问题