Home > other >  How can I refer to a named color located in package library's Assets.xcassets?
How can I refer to a named color located in package library's Assets.xcassets?

Time:12-21

I am developing a package library, so that I can share the code among multiple extensions.

I want to refer to a named color located in package's library Assets.xcassets.

enter image description here

The following code, which is written in the package library, is not working as expected.

let testColor = Color("whiteNoteColor")

It was not able locate whiteNoteColor defined in Assets.xcassets.

May I know, what is the correct way to do so? Thanks.

CodePudding user response:

You have to specify the bundle when the asset is held as part of a package. Try

let testColor = Color("whiteNoteColor", bundle: .module)

Note that this can be a little sketchy in SwiftUI previews, depending on the target.

If you want to access these colours outside the package, you should expose them as public properties defined like the above code - don't try and make Bundle.module public or let outside code try to use the named assets. It doesn't end well.

CodePudding user response:

To read the color from the assets, you must call it as a UIColor(named:) and turn it to type Color.

You can easily access the color by creating an extension to the type Color, than it becomes a color like any other.

Like this:

extension Color {
    
    static var whiteNoteColor: Color { Color(UIColor(named: "whiteNoteColor") ?? UIColor(Color.white)) }
}

You use it in your code:

Text("My text in white")
    .foregroundColor(.whiteNoteColor)  // Cal it as if it were a system color
  • Related