How to change Background Color of Button in SwiftUI

14 min read

To change the background color of a button in SwiftUI, you can use the background modifier and set it to a color.

Here's an example:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: {
            // Action to perform when the button is pressed
        }) {
            Text("Button")
                .foregroundColor(.white)
                .padding()
                .background(Color.blue) // Set the background color of button to blue
                .cornerRadius(10) // Optional: Add a corner radius to button
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example, the background(Color.blue) line sets the background color of the button to blue. You can replace Color.blue with any other color of your choice.

Additionally, you can chain other modifiers, such as padding() or cornerRadius(), to further customize the appearance of the button.