Muhammad Nabeel Arif
Muhammad Nabeel Arif

Reputation: 19310

SwiftUI: Unable to access colors from Common framework's Assets

I have a common framework shared by multiple applications. In my common framework, I have colors defined in assets. I use following code to access the colors within common framework.

public struct ColorTheme {
    public static let primaryColor = Color("primaryColor")
    public static let secondaryColor = Color("secondaryColor")
    public static let captionColor = Color("captionColor")
}

It works fine within the common framework. But as soon as I use the framework in my ZYZ app with syntax ColorTheme.primaryColor colors are not loaded and I get following error No color named 'primaryColor' found in asset catalog for main bundle

I know that colors are not in main bundle, but in common framework's bundle. Do you know how should we fix the issue, so we can acess those colors from common frameworks bundle using SwiftUI code?

Upvotes: 0

Views: 1382

Answers (1)

Muhammad Nabeel Arif
Muhammad Nabeel Arif

Reputation: 19310

Following code worked for me. As Color do not provides any initializer that accepts bundle, so we have to get UIColor first and then convert it to Color

public extension Bundle {
    static var commonBundle: Bundle {
        return Bundle(identifier: "com.mydomain.common")!
    }
}
extension Color {
    init(_ name: String, bundle: Bundle) {
        self.init(UIColor(named: name, in: bundle, compatibleWith: nil)!)
    }
}

After above extensions I updated my ColorTheme as follows

public struct ColorTheme {
    public static let primaryColor = Color("primaryColor", bundle: Bundle.commonBundle)
    public static let secondaryColor = Color("secondaryColor", bundle: Bundle.commonBundle)
    public static let captionColor = Color("captionColor", bundle: Bundle.commonBundle)
}

Upvotes: 1

Related Questions