问题描述
我在iOS和watchOS应用程序之间有一个共享框架,其中包含带有一些已命名颜色的资产目录。我想在我的watchOS应用中访问命名的颜色。在iOS中,我可以使用UIColor.init(named name: String,in bundle: Bundle,compatibleWith traitCollection: UITraitCollection)
告诉系统从传入的Bundle中访问名称。
watchOS还声称可以使用此初始化程序。但是,Xcode自动完成找不到,尝试使用它时出现构建错误,这有点奇怪,因为UITraitCollection
(属于该方法签名的一部分)在watchOS中没有暴露给我们无论如何。
如何在共享框架中从资产目录访问资产?
解决方法
不确定这是最好的解决方案,但我将iOS Assets.xcassets添加到了我的 目标成员面板中的WatchApp Extension可以解决此问题。
,这是一个 hack,但我创建了一个 objc 标头来使 UITraitCollection
定义可用于 watchOS。
这允许访问 UIColor(named name: String,in bundle: Bundle?,compatibleWith traitCollection: UITraitCollection?)
方法。
Objc 头文件添加到框架中:
#if TARGET_OS_WATCH
@import UIKit;
@interface UITraitCollection : NSObject
@end
#endif
,
我遇到了同样的问题,将提交反馈/雷达,但同时能够使用 SwiftUI 的 Color
对象,该对象具有 init(_ name: String,bundle: Bundle? = nil)
作为 watchOS 上的桥梁,并使用 {{ 1}} 构造函数以获取等效的 UIColor(Color)
实例。即:
UIColor
在我的特定情况下,我使用的实际代码是通过 UIColor、Color 和 Bundle 上的扩展公开的,因此我可以键入对资产目录和包的访问权限,但这本质上是引擎盖下的机制。