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

无法使用AWS Style Dictionary为UIFont创建自定义转换器求助

修复AWS Style Dictionary自定义转换器不生效,生成UIFont属性

问题场景

使用AWS Style Dictionary从Figma Tokens生成iOS平台的字体属性时,自定义的font/createUIFont转换器未生效,生成的FontTokens.swift中字体属性仍是原始字符串值,而非期望的UIFont实例代码:

当前输出:

public class FontTokens {
   public static let headingg = "HelveticaNeue-Bold"
}

期望输出:

public class FontTokens {
   public static let headingg = UIFont(name: "HelveticaNeue-Bold", size: 20) ?? UIFont.systemFont(ofSize: 20)
}

问题原因

  1. 依赖导入错误:使用了style-dictionary-utils而非核心库style-dictionary,导致registerTransform方法未正确绑定。
  2. Token属性获取错误:尝试从token.attributes.size.value获取字体大小,但$size属于自定义属性,会被直接解析为token.size,而非嵌套在attributes中。
  3. Transform执行顺序冲突:默认ios-swift-separate转换组包含的value/string转换会将自定义转换结果重新包装为带引号的字符串,覆盖预期输出。

修复方案

1. 修正依赖导入

替换原导入语句,直接使用核心库:

import StyleDictionary from 'style-dictionary';

2. 调整自定义转换器

修改转换器中获取字体大小的逻辑,并确保matcher正确匹配:

StyleDictionary.registerTransform({
  name: 'font/createUIFont',
  type: 'value',
  matcher: function(token) {
    return token.attributes.category === 'font';
  },
  transformer: function(token) {
    const fontName = token.value; // 直接使用token.value获取字体名称
    const fontSize = token.size; // 从token.size获取定义的字体大小

    return `UIFont(name: "${fontName}", size: ${fontSize}) ?? UIFont.systemFont(ofSize: ${fontSize})`;
  }
});

3. 调整平台转换配置

移除默认转换组,显式指定必要的转换步骤,避免冲突:

const config = {
  source: ["tokens/**/*tokens.json"],
  platforms: {
    "ios-swift-separate-enums": {
      "buildPath": "build/ios/",
      "files": [{
          "destination": "FontTokens.swift",
          "format": "ios-swift/class.swift",
          "className": "FontTokens",
          "filter": {
            "attributes": {
              "category": "font"
            }
          },
          "transforms": [
            "attribute/cti", // 解析Token的category-type-item属性
            "name/cti/camel", // 生成驼峰命名的属性名
            "font/createUIFont" // 执行自定义转换
          ]
        }]
    }
  },
};

StyleDictionary
  .extend(config)
  .buildAllPlatforms();

验证结果

重新执行构建命令后,生成的FontTokens.swift将输出预期的UIFont实例代码:

public class FontTokens {
   public static let headingg = UIFont(name: "HelveticaNeue-Bold", size: 20) ?? UIFont.systemFont(ofSize: 20)
}

内容的提问来源于stack exchange,提问作者Teja Nandamuri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:00:59