Szymon W
Szymon W

Reputation: 578

How to change a background color in whole App?

Is there a way to set up the background of the whole app (same default background for each view) in one place? For example in the SceneDelegate?

Upvotes: 9

Views: 3945

Answers (2)

Kai Chi Tsao
Kai Chi Tsao

Reputation: 41

import SwiftUI

struct TestView: View {
    var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(.blue)
                .edgesIgnoringSafeArea(.all)

            Text("Hello World!")
                .foregroundColor(.white)
        }
    }
}

ZStack and Rectangle(), Setting foregroundColor and edgesIgnoringSafeArea

demo

Upvotes: 4

user7014451
user7014451

Reputation:

Create a custom ViewModifier, throw in your color, and add it to your views. For instance, if you want all your views to be orange, do this:

struct BackgroundColorStyle: ViewModifier {

    func body(content: Content) -> some View {        
        return content
            .background(Color.orange)
    }
}

And usage is:

Text("Hello world!").modifier(BackgroundColorStyle())

Now, you can - and probably should - expand on this for light/dark mode. In this case, you can use the environment variable ColorSchmem:

struct BackgroundColorStyle: ViewModifier {
    @Environment (\.colorScheme) var colorScheme:ColorScheme    
    func body(content: Content) -> some View { 
        if colorScheme == .light {
            return content
                .background(Color.darkGrey)
        } else {
            return content
                .background(Color.white)
        }
    }
}

Either way, every View using this modifier has their background color defined in one place. If you wish to define a border along with a background color, same thing.

Upvotes: 5

Related Questions