iosswiftuiswiftui-previews

SwiftUI Preview not loading Color assets from .xcassets in framework target


I'm building a modular iOS app with SwiftUI views in a framework target (MyFrameworkTarget). I added a new .xcassets catalog to this target and defined some named colors like "durationBackground". The assets work at runtime, but in SwiftUI previews, the colors fail to load (they render as clear/black).

I tried the following-

Color("durationBackground", bundle: Bundle(identifier: "com.mycompany.MyFrameworkTarget"))

What is the correct way to load colors from an .xcassets catalog inside a SwiftUI framework target, so that SwiftUI previews can render them correctly?


Solution

  • if your Package is Internal:

    you should define your asset such as below structure:

    enter image description here

    and also in your "Package.swift" file should define your resource such as:

    `

    import PackageDescription
    
    let package = Package(
        name: "YourPackageName",
        platforms: [
             .iOS(.v13)
        ],
        products: [
            .library(
                name: "YourPackageName",
                targets: ["YourPackageName"]),
        ],
        targets: [
            .target(
                name: "YourPackageName",
                resources: [.process("Resources")]
            ),
        ]
    )
    

    this is required:

    resources: [.process("Resources")]
    

    if your Package is External:

    The problem maybe is for the bundle definition
    There are two solutions for the bundle definition if your package is external(it depends on your package manager pod or spm):

    var bundle = Bundle.module
    #if SWIFT_PACKAGE
            bundle = Bundle.module
    #else
            bundle = Bundle(for: self)
    #endif
    

    Check this link:
    How to define Bundle as internal For Pod Lib and SPM that handles both of them For using package images