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

如何引用Swift Package库Assets.xcassets中的命名颜色?

在Swift Package中引用Assets.xcassets内的命名颜色

问题原因

Swift Package的资源不会自动加入主Bundle,默认的Color(_:)初始化器只会在主Bundle中查找资源,所以直接调用找不到Package里的颜色。

解决步骤

1. 配置Package.swift,确保资源被正确打包

在你的Swift Package配置文件Package.swift中,给目标Target添加资源处理配置,确保Assets.xcassets被包含进Package的Bundle:

let package = Package(
    name: "YourPackageName",
    products: [
        .library(
            name: "YourPackageName",
            targets: ["YourPackageName"]),
    ],
    targets: [
        .target(
            name: "YourPackageName",
            resources: [
                // 处理Assets.xcassets资源
                .process("Assets.xcassets")
            ]),
        .testTarget(
            name: "YourPackageNameTests",
            dependencies: ["YourPackageName"]),
    ]
)

注意替换YourPackageName为你的实际Package名称,确保Assets.xcassets的路径正确(如果不在Target根目录,要调整路径)。

2. 引用颜色时指定Package的Bundle

Swift Package提供了自动生成的Bundle.module属性,用来获取当前Package的Bundle,初始化Color时传入这个Bundle即可:

直接调用方式

let testColor = Color("whiteNoteColor", bundle: Bundle.module)

封装扩展(推荐,方便复用)

可以给Color添加静态属性,封装Bundle的引用:

import SwiftUI

extension Color {
    static let whiteNoteColor = Color("whiteNoteColor", bundle: .module)
}

// 使用示例
let testColor = Color.whiteNoteColor

额外注意事项

  • 颜色名称大小写敏感,确保和Assets.xcassets中的命名完全一致
  • 如果是使用UIKit的UIColor,方法类似:
let testUIColor = UIColor(named: "whiteNoteColor", in: .module, compatibleWith: nil)

内容的提问来源于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.07 17:41:07