2

I'm building a custom view wrapping a UIView with UIViewRepresentable.

How can I get access to some of the environment values (for example, to the foreground color, but the question is more general) that was set at the parent level.

For example, this works as expected with normal SwiftUI:

var body: some View {
   Group {
      Text("Will be red")
   }.foregroundColor(.red)
}

So, somehow SwiftUI knows to set the color of the Text view as red.

But if, instead of Text above, I want to use my own CustomText: UIViewRepresentable, how would I get the foreground color?

struct CustomText: UIViewRepresentable {
    func makeUIView(context: Context) -> UITextView {
        let text = UITextView()
        text.textColor = ?? // <-- how do I set this based on environment
        text.text = "CustomText"
        return text
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        
    }
}

I thought I could get it from context.environment, which is an EnvironmentValues type, but it's not available through its properties.

EnvironmentValues supports subscript(_:) for dynamic member lookup, but it expects a EnvironmentKey type as a parameter. What is the environment key of the foreground color? Is there a way to query all the environment keys that were set?

New Dev
  • 48,427
  • 12
  • 87
  • 129

0 Answers0