在 SwiftUI 中,如何访问 UIViewRepresentable 中 .foregroundColor 和其他修饰符的当前值?

Dra*_*rok 18 ios swift swiftui

给出以下示例代码:

struct ActivityIndicatorView : UIViewRepresentable {
    var style: UIActivityIndicatorView.Style = .medium

    func makeUIView(context: UIViewRepresentableContext<ActivityIndicatorView>) -> UIActivityIndicatorView {
        return UIActivityIndicatorView(style: style)
    }

    func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicatorView>) {
        uiView.color = UIColor.white // how would I set this to the current .foregroundColor value?
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何找出当前值.foregroundColor(…)以正确呈现我的 UIView?

我已经阅读了这个问题,但这是从外部检查 ModifiedContent 的角度来看的,而不是包装的 View。

LuL*_*aGa 2

无法访问前景色,但您可以访问配色方案并据此确定活动指示器的颜色:

struct ActivityIndicatorView : UIViewRepresentable {

   @Environment(\.colorScheme) var colorScheme: ColorScheme

    //...

    func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicatorView>) {

        switch colorScheme {
        case .dark:
            uiView.color = .white
        case .light:
            uiView.color = .black
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这很令人失望。想知道应用了哪些修饰符似乎是一件很正常的事情,尤其是当它们是元素颜色这样的核心内容时!希望苹果能够在未来的版本中解决这个问题...... (14认同)