Change the background color of a Form in SwiftUI

You have landed on this page which means that you are also frustrated getting the same grey background color in your Form in SwiftUI. Now if you wish to change that background color then you probably have tried this:

  • .background(.colorName)

But believe me, this will not work until you hide the default background.

Let’s get the solution first and then I can elaborate on it.

.scrollContentBackground(.hidden)

Adding the above-mentioned modifier is enough to hide the default background of the Form view.

An example will be better for you:

import SwiftUI

struct ContentView: View {
    @State private var name = ""
    
    var body: some View {
        Form{
            Text("Hello CodeSpeedy!")
        }
        .background(.red)
    }
}

The output will be like this:

Change the background color of a Form in SwiftUI

As you can see I have used: .background(.red)but still it won’t change the background color of our SwiftUI form.

To fix this we just need to do this:

import SwiftUI

struct ContentView: View {
    @State private var name = ""
    
    var body: some View {
        Form{
            Text("Hello CodeSpeedy!")
        }
        .scrollContentBackground(.hidden) // This line will hide the default background
        .background(.red)
    }
}

Output:

Form background color change SwiftUI

Note: I have tried the same code on MacOS project for this form but in my case, .background(.colorName)worked fine without using .scrollContentBackground(.hidden).

Because technically Form is different for iOS and MacOS. On the other hand, List view is similar for both MacOS and iOS.

Leave a Reply

Your email address will not be published. Required fields are marked *