UIViewRepresentable视图如何获取在父级设置的环境属性

时间:2020-08-24 16:26:10

标签: swift swiftui

我正在构建将UIViewUIViewRepresentable包裹在一起的自定义视图。

我如何访问在父级设置的某些环境值(例如,前景色,但问题更笼统)。

例如,这可以正常使用SwiftUI:

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

因此,SwiftUI以某种方式知道将Text视图的颜色设置为红色。

但是,如果我想使用我自己的Text而不是上面的CustomText: UIViewRepresentable,我将如何获得前景色?

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) {
        
    }
}

我以为我可以从context.environment类型的EnvironmentValues获取它,但是它不能通过其属性来使用。

EnvironmentValues支持subscript(_:)进行动态成员查找,但是它期望使用EnvironmentKey类型作为参数。前景色的环境关键是什么?有没有办法查询设置的所有环境键?

0 个答案:

没有答案