在SwiftUI中,将swift应用中的所有Text()变成相同的颜色。

问题描述 投票:0回答:1

我在Swift Playground应用中多次使用Text("")对象,但我想把所有对象的颜色都改为特定的颜色(白色),而不逐一改变每个Text属性。有什么方法可以做到这一点吗?

免责声明:我是在Swift Playground中编程的。 我在Swift Playground中编程

swift swiftui swift-playground
1个回答
1
投票

你可以创建一个自定义的 ViewModifier

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

然后你就可以把它应用到 Text 在需要的地方,你只需要在ViewModifier结构中改变它。

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

2
投票

您可以创建您自己的 View 其身为 Text 而这有 color 属性,您将其用作 foregroundColor 你的 Text. 如果你做了 color 财产 static的所有实例,它将适用于您的 View.

你只需要确保你使用 ColoredText 而不是 Text 在所有您想要相同颜色的地方,如果您改变了 ColoredText.color所有实例都将应用新的文本颜色。

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

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

1
投票

如果你想改变所有的文字颜色,你可以使用这个。

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World")
            Text("aha")
            Button(action: {}) {
                  Text("Tap here")
              }
            }.colorInvert()
        .colorMultiply(Color.red)
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.