Search code examples
swiftswiftuiswiftui-form

Give Form Section a Background Color/Gradient


This is my code:

Form {
  Section {} // regular section no background

  Section { // <--- want this section to have a background color
     Text("Hello")
  }
  .background(Gradient(colors: [.teal, .cyan, .green]).opacity(0.6))

} // Do not want background on form only on an individual section

This only puts a background on the Text(), which makes sense, but how do I get it to apply the background just the section


Solution

  • You need to use .listRowBackground and apply a gradient as the background style. See below:

    Form {
          Section {} // regular section no background
    
          Section { // <--- want this section to have a background color
             Text("Hello")
          }
          .listRowBackground(LinearGradient(gradient: Gradient(colors: [.teal, .cyan, .green]), startPoint: .leading, endPoint: .trailing))
            
    } // Do not want background on form only on an individual section
    

    enter image description here