You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何引用Package库Assets.xcassets中的命名UIColor?

解决Package库中UIColor无法引用Assets颜色的问题

问题出在UIColor(named:)默认会从主Bundle里查找资源,而你的颜色资源存放在Package的独立模块Bundle中,必须显式指定Bundle参数才能定位到。

直接使用带Bundle参数的UIColor初始化方法即可,和SwiftUI.Color的用法逻辑一致:

// 确保颜色资源存在时,可直接强制解包
UIColor(named: "whiteNoteColor", in: .module, compatibleWith: nil)!

// 更安全的可选绑定写法,避免资源缺失导致崩溃
if let whiteNoteColor = UIColor(named: "whiteNoteColor", in: .module, compatibleWith: nil) {
    // 在这里使用获取到的颜色
}

关键说明

Swift Package的资源会被打包到专属的模块Bundle里,Bundle.module是Swift Package自动生成的属性,专门指向当前Package的Bundle路径,通过它就能正确访问到Assets.xcassets中存储的命名颜色。

内容的提问来源于stack exchange,提问作者Cheok Yan Cheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:25:32