48

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.

wictorious
  • 851
  • 3
  • 10
  • 24

5 Answers5

41

enter image description here

Button(action: { }) {
    Text("Button Text!").padding()
}
.background(Color.black)
Daniel
  • 1,473
  • 3
  • 33
  • 63
32

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!

Tuan Nguyen
  • 2,624
  • 1
  • 17
  • 15
31

Also in SwiftUI, if you're using the .buttonStyle and want to change the background color, you'd use .tint, not .background. For example, this is how you can change a borderedProminent button style to green:

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

enter image description here

Gallaugher
  • 1,593
  • 16
  • 27
11
            Button(action: {self.buttonTapped()}) {
            Text("Button")
                .padding(.all, 12)
                .foregroundColor(.white)
                .background(Color.red)
        }

that's how the whole bg is clickable

Bassem Tourky
  • 482
  • 5
  • 12
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

yoAlex5
  • 29,217
  • 8
  • 193
  • 205