How to access color from an asset catalog in a shared framework in a watchOS app?

Viewed 712

I have a shared framework between my iOS and watchOS apps which contains an asset catalog with some named colors. I'd like to access the named colors in my watchOS app. In iOS, I can use UIColor.init(named name: String, in bundle: Bundle, compatibleWith traitCollection: UITraitCollection) to tell the system to access the name from the passed-in Bundle.

watchOS also claims to have this initializer available since watchOS 4; however, Xcode autocomplete doesn't find it, I get a build error when I try to use it, and it's a bit odd because UITraitCollection (which is part of that method signature) isn't exposed to us in watchOS anyhow.

How can I access an asset from the asset catalog in my shared framework?

3 Answers

Not certain this is the best solution but I added my iOS Assets.xcassets to my WatchApp Extension in the target Membership Panel and this solved the issue.

I had the same issue and will file a feedback/radar, but in the meantime was able to use SwiftUI's Color object, which has init(_ name: String, bundle: Bundle? = nil) as a bridge on watchOS, and use the UIColor(Color) constructor to obtain an equivalent UIColor instance. ie:

UIColor(Color("myColor", bundle: myBundle))

In my particular case, the actual code I'm using is exposed via extensions on UIColor, Color and Bundle so that I have typed access to the asset catalog and bundle, but thats essentially the machinery under the hood.

This is a hack, but I created an objc header to make the UITraitCollection definition available to watchOS. This allowed for the UIColor(named name: String, in bundle: Bundle?, compatibleWith traitCollection: UITraitCollection?) method to be accessed.

Objc header file added to the framework:

#if TARGET_OS_WATCH

@import UIKit;

@interface UITraitCollection : NSObject

@end

#endif
Related