'Change GroupBox background color in SwiftUI

How can I change the default gray background color of a GroupBox view in SwiftUI?

I tried adding a background modifier, but this just changes the white background underneath the box (see screenshot).

GroupBox(label: Text("Label"), content: {
    Text("Content")
})
.background(Color.blue)

SwiftUI GroupBox screencapture with gray background and blue corners



Solution 1:[1]

This is default group box style. You can create whatever group box needed using custom style.

Here is an example. Tested with Xcode 12 / iOS 14.

demo

struct DemoGroupBox: View {
    var body: some View {
        GroupBox(label: Text("Label"), content: {
             Text("Content")
        })
        .groupBoxStyle(TransparentGroupBox())
        .padding()
    }
}

struct TransparentGroupBox: GroupBoxStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.content
            .frame(maxWidth: .infinity)
            .padding()
            .background(RoundedRectangle(cornerRadius: 8).fill(Color.blue))
            .overlay(configuration.label.padding(.leading, 4), alignment: .topLeading)
    }
}

backup

Solution 2:[2]

Try an overlay modifier with whatever you want. If you use .fill inside the overlay, it will change the background color but it will also cover the underlying views.

I used a stroked and clear RoundedRectangle view instead of a .fill. It's an easy way to style your GroupBox.

.overlay(
   RoundedRectangle(cornerRadius: 15)
      .stroke(Color.purple, lineWidth: 5)
  )    

Solution 3:[3]

Short answer: it is currently not properly supported by SwiftUI :(

Longer answer: you can create a custom GroupBoxStyle (see example) which will allow you to change the background... but at the cost of having to then manually layout the contents (which somewhat defeats the purpose).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Cihan
Solution 3