Can I override the black background color in SwiftUI dark mode?

Viewed 672

I'm trying to change the black background color globally (app-wide) in SwiftUI dark mode, but I can't find a way to do so, the .background(View) modified changes only the background for the view it's applied to, which is not what I'm looking for!

I tried overriding the UIColor.systemBackground but it doesn't seem to have any effect actually!

Edit: here's a screenshot of what I have right now and what I'm looking for!

enter image description here

1 Answers

Well, I figure out how to achieve the desired result, here's what I did.

  1. Create a color set with the background color you want.
  2. Create a color extension for ease of use.
extension Color {
    static let systemBackground = Color("Background")
}
  1. In your ContentView.
init() {
    UINavigationBar.appearance().backgroundColor = UIColor(Color.systemBackground)
    UITableView.appearance().backgroundColor = UIColor(Color.systemBackground)
    UITableViewCell.appearance().backgroundColor = UIColor(Color.systemBackground)
}

var body: some View {
    ZStack {
        Color.systemBackground
            .edgesIgnoringSafeArea(.vertical)

        MyContent()    
    }
}
  1. And then if MyContent is a List.
struct MyContent: View {
    var body: some View {
        List {
            ForEach(items) {
                ItemRow($0)
            }
            .listRowBackground(Color.systemBackground)
        }
    }
}

Please note that the .listRowBackground modified is applied to the ForEach, not the List.

  1. And finally if MyContent is a ScrollView or any other custom view you can simply use the background modified on it.

here's the final result.

enter image description here


I was expecting to override the UIColor.systemBackground as @swiftpunk mentioned in his answer and all of the views will pick up the new color automatically but it turned out that it just has no effect at all. ‍♂️

Related