59

What is the best way to change the button's background color in SwiftUI?

I want to create a tile which is a button with centered Text and rectangular background of some color.

5 Answers 5

52

If you're using the .buttonStyle(style:) modifier and want to change the background color, use .tint(tint:) and not .background(alignment:content). For example, this is how you can change a .borderedProminent button style to green:

Button("Press Me!") {
    //stuff to do
}
.buttonStyle(.borderedProminent)
.tint(.green)

Button screenshot

Sign up to request clarification or add additional context in comments.

1 Comment

this is for above and ios 15, below ios 15 .background(Color.black)
43

enter image description here

Button("Button Text!") {
   //Action here
}
.background(Color.black)

2 Comments

This one don't compile when button is in a VStack
How can I apply corner radius ?
36

enter image description here

You can add a modified directly to the button without any containers (ex: Group)

Button(action: {}) {
    Text("Click me!")
}
.padding()
.foregroundColor(.white)
.background(Color.red)

Hoping to help someone!

1 Comment

how come . background(Color("Blue")) doesn't work when you have a color set in the assets folder?!
11
            Button(action: {self.buttonTapped()}) {
            Text("Button")
                .padding(.all, 12)
                .foregroundColor(.white)
                .background(Color.red)
        }

that's how the whole bg is clickable

1 Comment

this seems strange but it is the right way to customize background color in the button
0

SwiftUI color

From iOS v13 and above, when you work with colors you should take into account Light and Dark mode.

.foregroundColor(.red)
.background(.blue)

For example .black in dark mode will be invisible(black on black). You can use system colors as a variant. For example UIColor.label

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.