How to override styles in SwiftUI

Issue #688

In the app I’m working on Elegant Converter, I usually like preset theme with a custom background color and a matching foreground color.

Thanks to SwiftUI style cascading, I can just declare in root MainView and it will be inherited down the view hierachy.

1
2
3
4
5
6
7
8
9
10
struct MainView: View {
var body: some View {
HSplitView {
ListView()
RightView()
}
.foregroundColor(R.color.text)
.background(R.color.background)
}
}

This works great regardless of system light or dark mode, but in light mode it does not look good, as my designed theme is similar to dark mode. Here the color is pale for default Picker and Button.

Screenshot 2020-10-31 at 06 49 55

The way to fix that is to reset the foregroundColor, take a look at the documentation for foregroundColor

The foreground color to use when displaying this view. Pass nil to remove any custom foreground color and to allow the system or the container to provide its own foreground color. If a container-specific override doesn’t exist, the system uses the primary color.

So we can pass nil and the controls will pick the correct color based on system preferences.

1
2
3
4
5
6
7
8
9
10
11
Picker(selection: intent.fileType, label: EmptyView()) {
ForEach(filtered, id: \.self) {
Text($0.dropdownName)
}
}
.foregroundColor(nil)

Button(action: convert) {
Text("Convert")
}
.foregroundColor(nil)

Now Picker and Button look nice in both dark and light mode

Screenshot 2020-10-31 at 06 52 53 Screenshot 2020-10-31 at 06 53 10

Comments