I have list of named color re-inside package library's Assets.xcassets
SwiftUI.Color
For SwiftUI.Color, I can access them without issue.
SwiftUI.Color("whiteNoteColor", bundle: .module)
UIColor
However, how about UIColor
?
I have tried the following but it doesn't work
UIColor(named: "whiteNoteColor")!
Does anyone know, how can I refer to a named UIColor located in package library's Assets.xcassets?
CodePudding user response:
If you add an extension
to the Package You can access it directly.
extension UIColor{
static let whiteNoteColor: UIColor = UIColor(named: "whiteNoteColor")!
}
You can access UIColor.whiteNoteColor
when you import YourPackage
CodePudding user response:
To use a named color from your package library's Assets.xcassets file in a UIKit element, you can use the UIColor(named:in:compatibleWith:) initializer. This initializer takes a name, a bundle, and a trait collection as arguments.
Here's an example of how you can use this initializer to create a UIColor from a named color in your Assets.xcassets file:
let color = UIColor(named: "whiteNoteColor", in: .module, compatibleWith: nil)
The in: parameter specifies the bundle that contains the color asset. In this case, we're using the .module bundle to refer to the current module (your package library).
The compatibleWith: parameter specifies a trait collection that the color should be compatible with. You can pass nil if you don't need to specify a trait collection.
Keep in mind that this initializer can return nil if the named color is not found in the specified bundle. To handle this possibility, you can use optional binding or the nil-coalescing operator (??) to provide a default value.
For example:
let color = UIColor(named: "whiteNoteColor", in: .module, compatibleWith: nil) ?? .white
This will use the whiteNoteColor color if it's available, or fall back to the default .white color if it's not.