wictorious
wictorious

Reputation: 961

How can I change background color of button in SwiftUI?

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.

Upvotes: 56

Views: 56902

Answers (5)

Daniel
Daniel

Reputation: 1057

enter image description here

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

Upvotes: 43

Gallaugher
Gallaugher

Reputation: 1971

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

Upvotes: 45

yoAlex5
yoAlex5

Reputation: 34471

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

Upvotes: 0

Tuan Nguyen
Tuan Nguyen

Reputation: 2744

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!

Upvotes: 35

Bassem Tourky
Bassem Tourky

Reputation: 487

            Button(action: {self.buttonTapped()}) {
            Text("Button")
                .padding(.all, 12)
                .foregroundColor(.white)
                .background(Color.red)
        }

that's how the whole bg is clickable

Upvotes: 11

Related Questions