Reputation: 961
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
Reputation: 1057
Button("Button Text!") {
//Action here
}
.background(Color.black)
Upvotes: 43
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)
Upvotes: 45
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
Reputation: 2744
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
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