Turn all Text() on swift app to the same color in SwiftUI

Viewed 944

I have used the Text("") object multiple times in my Swift Playground app but I want to change the color of all of them to a specific color (white) without changing each Text property one by one. Is there a way to do this?

Disclaimer: I am programming in a Swift Playground

3 Answers

You can create a custom ViewModifier

struct MyTextModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .foregroundColor(Color.white)
    }
}

Then you can apply it to Text where needed, and you only need to change it in the ViewModifier struct.

struct ContentView: View {
    var body: some View {
        Text("Your Text")
            .modifier(MyTextModifier())
    }
}

You can create your own View whose body is a Text and that has a color property that you use as the foregroundColor of your Text. If you make the color property static, it will apply to all instances of your View.

You just need to make sure you use ColoredText instead of Text in all places where you want the same color and if you change ColoredText.color, all instances will apply the new text color.

struct ColoredText: View {
    @State static var color: Color = .primary
    @State var text: String

    var body: some View {
        Text(text)
            .foregroundColor(ColoredText.color)
    }
}

if you want to change ALL you can use this:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World")
            Text("aha")
            Button(action: {}) {
                  Text("Tap here")
              }
            }.colorInvert()
        .colorMultiply(Color.red)
    }
  }
Related