Reputation: 11
The button text does not change colors properly when switching between light and dark mode. In light mode it shows up as a black button with white text. in dark mode it just shows a white button with assumably white text. I'm looking to apply a style that adapts automatically in light/dark mode.
struct Primary: View {
var body: some View {
Button("hello") {}
.buttonStyle(.borderedProminent)
.tint(.primary)
// .disabled(true) // optional
}
}
I've tried splitting the Button init so i can modify the text directly but with no success. It shows up correctly when adding the .disabled modifier.
Clarification: I am looking for a way to inverse the colors of the button in dark mode while preserving the .disabled color scheme of primary. I would prefer to avoid a bunch of if statements if possible.
I've added text on the image for the bottom left. This is the result i'm looking to achieve for the button when going through light/dark, disabled/enabled. link to image
Upvotes: 0
Views: 304
Reputation: 21740
The default color of a bordered-prominent button is blue in both light and dark modes. The foreground color for the label is white in both cases.
When you apply .tint
, it overrides the default accent color. In the case of a bordered-prominent button, it is used instead of blue for the background. But it doesn't change the foreground color.
Since you are using the primary foreground color for the background, it might make sense to use the background color for the foreground. The modifier .foregroundStyle
can be used for this:
Button("hello") {}
.buttonStyle(.borderedProminent)
.tint(.primary)
.foregroundStyle(.background) // <- ADDED
Alternatively, you can determine whether light or dark mode is in operation using the environment value colorScheme
. You can then set the foreground style explicitly:
@Environment(\.colorScheme) private var colorScheme
Button("hello") {}
.buttonStyle(.borderedProminent)
.tint(.primary)
.foregroundStyle(colorScheme == .dark ? .black : .white)
Upvotes: 1
Reputation: 924
You can directly set the text color using .foregroundColor()
modifier within the Button
initializer. Using .primary
as the color ensures it automatically adjusts based on the appearance mode. Here's an example:
struct Primary: View {
var body: some View {
Button(action: {}) {
Text("hello")
.foregroundColor(.primary) // Adjusts text color for light/dark mode
}
.buttonStyle(.borderedProminent)
.tint(.primary) // Adjusts button's background and border color
}
}
Upvotes: -1