Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SwiftUI, how can I access the current value of .foregroundColor and other modifiers inside my UIViewRepresentable?

Tags:

ios

swift

swiftui

Given the following example code:

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?
    }
}

How do I find out the current value of .foregroundColor(…) in order to render my UIView correctly?

I have read this question but that is from the perspective of inspecting the ModifiedContent from the outside, not the wrapped View.

like image 319
Drarok Avatar asked Sep 03 '19 12:09

Drarok


People also ask

What is Uiviewrepresentable SwiftUI?

A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.

How do I use custom colors in SwiftUI?

Adding custom colors is actually simple, you add the color to the assets folder and then you write a few lines of code to use it anywhere you want in your project. Search for the assets folder in your project, once inside you'll see everything that's added to the folder such as images, your app icon, etc.


2 Answers

There is no way to access the foreground colour but you can access the colour scheme and determine the colour of your activity indicator based on that:

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
        }

    }
}
like image 108
LuLuGaGa Avatar answered Sep 22 '22 11:09

LuLuGaGa


Agreed, this should be addressed. I took a stab at trying to pull this value out of the Environment and this is what I got. Looks like the EnvironmentKey exists, but is internal :( enter image description here

like image 40
Jack Avatar answered Sep 21 '22 11:09

Jack