Communitygithub.com

本地化与国际化

全面的应用本地化指南,涵盖字符串目录、复数处理、RTL布局、区域感知格式化及从传统 .strings 文件迁移等 iOS 开发国际化模式。

本地化与国际化 是什么?

此技能为 iOS/macOS 开发者提供了使用 String Catalogs (.xcstrings) 进行应用本地化和国际化的完整指南。它详细介绍了 Xcode 15+ 中引入的统一格式,该格式取代了传统的 .strings 和 .stringsdict 文件,支持更轻松的维护、差异比较以及与翻译工作流的集成。技能涵盖了从创建 String Catalog、使用 SwiftUI 和 UIKit 的本地化 API,到处理英语、俄语、阿拉伯语等多种语言的复数规则,以及通过语义布局和图像翻转实现 RTL (Right-to-Left) 语言支持。此外,还包括日期、数字、货币的区域感知格式化,App Shortcuts 的本地化,以及 Xcode 26+ 中自动符号生成和 AI 注释生成等高级特性。该技能支持 iOS 15+ 及 Xcode 15+ 平台,并提供了从传统格式迁移的具体策略和最佳实践。

兼容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/IGTA-Tech/claude-skills-research/tree/HEAD/Axiom/.claude-plugin/plugins/axiom/skills/localization

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

本地化与国际化 是做什么的?

使用字符串目录进行应用本地化的综合指南。Apple 设计奖包容性获奖者始终支持多种语言并拥有出色的 RTL(从右到左)支持。

概述

字符串目录 (.xcstrings) 是 Xcode 15 用于管理应用本地化的统一格式。它们用单一的基于 JSON 的格式取代了传统的 .strings 和 .stringsdict 文件,这种格式更易于维护、比较差异并与翻译工作流集成。

本技能涵盖字符串目录、SwiftUI/UIKit 本地化 API、复数处理、RTL 支持、区域感知格式化以及从传统格式的迁移策略。

何时使用此技能

  • 在 Xcode 15+ 中设置字符串目录
  • 本地化 SwiftUI 和 UIKit 应用
  • 正确处理复数形式(对许多语言至关重要)
  • 支持 RTL 语言(阿拉伯语、希伯来语)
  • 根据区域格式化日期、数字和货币
  • 从传统的 .strings/.stringsdict 文件迁移
  • 为本地化准备 App Shortcuts 和 App Intents
  • 调试缺失的翻译或不正确的复数形式

系统要求

  • Xcode 15+:字符串目录 (.xcstrings)
  • Xcode 26+:自动符号生成、#bundle 宏和 AI 驱动的注释生成
  • iOS 15+:LocalizedStringResource
  • iOS 16+:App Shortcuts 本地化
  • 更早的 iOS 版本使用传统的 .strings 文件

第 1 部分:字符串目录 (WWDC 2023/10155)

创建字符串目录

方法 1:Xcode 导航器

  1. 文件 → 新建 → 文件
  2. 选择“字符串目录”
  3. 命名(例如 Localizable.xcstrings)
  4. 添加到目标

方法 2:自动提取

Xcode 15 可以自动从以下位置提取字符串:

  • SwiftUI 视图(Text、Label、Button 中的字符串字面量)
  • Swift 代码(String(localized:))
  • Objective-C(NSLocalizedString)
  • C(CFCopyLocalizedString)
  • Interface Builder 文件(.storyboard、.xib)
  • Info.plist 值
  • App Shortcuts 短语

需要构建设置:

  • “使用编译器提取 Swift 字符串” → 是
  • “本地化首选字符串目录” → 是

字符串目录结构

每个条目包含:

  • 键:唯一标识符(默认:英文字符串)
  • 默认值:缺少翻译时的后备文本
  • 注释:为翻译人员提供的上下文
  • 字符串表:组织容器(默认:“Localizable”)

示例 .xcstrings JSON:

{
  "sourceLanguage" : "en",
  "strings" : {
    "Thanks for shopping with us!" : {
      "comment" : "结账按钮上方的标签",
      "localizations" : {
        "en" : {
          "stringUnit" : {
            "state" : "translated",
            "value" : "Thanks for shopping with us!"
          }
        },
        "zh" : {
          "stringUnit" : {
            "state" : "translated",
            "value" : "感谢您与我们购物!"
          }
        }
      }
    }
  },
  "version" : "1.0"
}

翻译状态

Xcode 跟踪每个翻译的状态:

  • 新建 (⚪) - 字符串尚未翻译
  • 需要审核 (🟡) - 源字符串已更改,翻译可能已过时
  • 已审核 (✅) - 翻译已批准且为最新
  • 过期 (🔴) - 源代码中不再找到该字符串

工作流程:

  1. 开发者添加字符串 → 新建
  2. 翻译人员添加翻译 → 已审核
  3. 开发者更改源字符串 → 需要审核
  4. 翻译人员更新 → 已审核
  5. 开发者删除代码 → 过期

第 2 部分:SwiftUI 本地化

LocalizedStringKey(自动)

带有 String 参数的 SwiftUI 视图自动支持本地化:

// ✅ 自动可本地化
Text("欢迎使用 WWDC!")
Label("感谢您与我们购物!", systemImage: "bag")
Button("结账") { }

// Xcode 将这些字符串提取到字符串目录中

工作原理:SwiftUI 内部使用 LocalizedStringKey,它会在字符串目录中查找字符串。

带注释的 String(localized:)

用于在 Swift 代码中显式本地化:

// 基本用法
let title = String(localized: "欢迎使用 WWDC!")

// 带有为翻译人员提供的注释
let title = String(localized: "欢迎使用 WWDC!",
                   comment: "通知横幅标题")

// 使用自定义表
let title = String(localized: "欢迎使用 WWDC!",
                   table: "WWDCNotifications",
                   comment: "通知横幅标题")

// 带有默认值(键 ≠ 英文字符串)
let title = String(localized: "WWDC_NOTIFICATION_TITLE",
                   defaultValue: "欢迎使用 WWDC!",
                   comment: "通知横幅标题")

最佳实践:始终包含 comment 以为翻译人员提供上下文。

LocalizedStringResource(延迟本地化)

用于将可本地化字符串传递给其他函数:

import Foundation

struct CardView: View {
    let title: LocalizedStringResource
    let subtitle: LocalizedStringResource

    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 10.0)
            VStack {
                Text(title)      // 在渲染时解析
                Text(subtitle)
            }
            .padding()
        }
    }
}

// 用法
CardView(
    title: "最近购买",
    subtitle: "您过去一周订购的商品。"
)

关键区别:LocalizedStringResource 将查找操作推迟到使用时,允许自定义视图完全可本地化。

带 Markdown 的 AttributedString

// Markdown 格式在本地化之间保持不变
let subtitle = AttributedString(localized: "**粗体** 和 _斜体_ 文本")

第 3 部分:UIKit 和 Foundation

NSLocalizedString 宏

// 基本用法
let title = NSLocalizedString("最近购买", comment: "按钮标题")

// 带表名
let title = NSLocalizedString("最近购买",
                             tableName: "Shopping",
                             comment: "按钮标题")

// 带 bundle
let title = NSLocalizedString("最近购买",
                             tableName: nil,
                             bundle: .main,
                             value: "",
                             comment: "按钮标题")

Bundle.localizedString

let customBundle = Bundle(for: MyFramework.self)
let text = customBundle.localizedString(forKey: "欢迎",
                                        value: nil,
                                        table: "MyFramework")

自定义宏

// Objective-C
#define MyLocalizedString(key, comment) \
    [myBundle localizedStringForKey:key value:nil table:nil]

Info.plist 本地化

本地化应用名称、权限等:

  1. 选择 Info.plist
  2. 编辑器 → 添加本地化
  3. 为每种语言创建 InfoPlist.strings:
// InfoPlist.strings (中文)
"CFBundleName" = "我的应用";
"NSCameraUsageDescription" = "此应用需要访问相机以拍摄照片。";

第 4 部分:复数化

不同语言有不同的复数规则:

  • 英语:2 种形式 (one, other)
  • 俄语:3 种形式 (one, few, many)
  • 波兰语:3 种形式 (one, few, other)
  • 阿拉伯语:6 种形式 (zero, one, two, few, many, other)

SwiftUI 复数处理

// Xcode 自动创建复数变体
Text("\(count) 个项目")

// 带自定义格式
Text("\(visitorCount) 位近期访客")

在字符串目录中:

{
  "strings" : {
    "%lld 位近期访客" : {
      "localizations" : {
        "en" : {
          "variations" : {
            "plural" : {
              "one" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "%lld Recent Visitor"
                }
              },
              "other" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "%lld Recent Visitors"
                }
              }
            }
          }
        },
        "zh" : {
          "variations" : {
            "plural" : {
              "other" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "%lld 位近期访客"
                }
              }
            }
          }
        }
      }
    }
  }
}

XLIFF 导出格式

导出翻译时(文件 → 导出本地化):

传统 (stringsdict):

<trans-unit id="/%lld Recent Visitors:dict/NSStringLocalizedFormatKey:dict/:string">
    <source>%#@recentVisitors@</source>
</trans-unit>

<trans-unit id="/%lld Recent Visitors:dict/recentVisitors:dict/one:dict/:string">
    <source>%lld Recent Visitor</source>
    <target>%lld Visitante Recente</target>
</trans-unit>

字符串目录(更简洁):

<trans-unit id="%lld Recent Visitors|==|plural.one">
    <source>%lld Recent Visitor</source>
    <target>%lld Visitante Recente</target>
</trans-unit>

<trans-unit id="%lld Recent Visitors|==|plural.other">
    <source>%lld Recent Visitors</source>
    <target>%lld Visitantes Recentes</target>
</trans-unit>

带复数变量的替换

// 多个具有不同复数形式的变量
let message = String(localized: "\(songCount) 首歌曲,共 \(albumCount) 张专辑")

Xcode 为每个变量的复数形式创建变体:

  • songCount: one, other
  • albumCount: one, other
  • 总组合数:2 × 2 = 4 个翻译条目

第 5 部分:设备和宽度变体

设备特定字符串

不同平台的不同文本:

// 相同代码,不同设备使用不同字符串
Text("鸟食商店")

字符串目录变体:

{
  "鸟食商店" : {
    "localizations" : {
      "en" : {
        "variations" : {
          "device" : {
            "applewatch" : {
              "stringUnit" : {
                "value" : "鸟食"
              }
            },
            "other" : {
              "stringUnit" : {
                "value" : "鸟食商店"
              }
            }
          }
        }
      }
    }
  }
}

结果:

  • iPhone/iPad:"鸟食商店"
  • Apple Watch:"鸟食"(为小屏幕缩短)

宽度变体

用于动态类型和尺寸类别:

Text("应用程序设置")

字符串目录可以为窄宽度提供更短的文本。


第 6 部分:RTL 支持

布局镜像

SwiftUI 会自动为 RTL 语言镜像布局:

// ✅ 自动为阿拉伯语/希伯来语镜像
HStack {
    Image(systemName: "chevron.right")
    Text("下一个")
}

// iPhone (英语):[>] 下一个
// iPhone (阿拉伯语):下一个 [<]

Leading/Trailing 与 Left/Right

始终使用语义方向:

// ✅ 正确 - 自动镜像
.padding(.leading, 16)
.frame(maxWidth: .infinity, alignment: .leading)

// ❌ 错误 - 不会镜像
.padding(.left, 16)
.frame(maxWidth: .infinity, alignment: .left)

图像和图标

标记应该/不应该翻转的图像:

// ✅ 方向性 - 为 RTL 镜像
Image(systemName: "chevron.forward")

// ✅ 非方向性 - 从不镜像
Image(systemName: "star.fill")

// 自定义图像
Image("backButton")
    .flipsForRightToLeftLayoutDirection(true)

在 RTL 模式下测试

Xcode 方案:

  1. 编辑方案 → 运行 → 选项
  2. 应用语言:阿拉伯语 / 希伯来语
  3. 或者:应用语言 → 从右到左伪语言

模拟器: 设置 → 通用 → 语言与地区 → 首选语言顺序

SwiftUI 预览:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environment(\.layoutDirection, .rightToLeft)
            .environment(\.locale, Locale(identifier: "ar"))
    }
}

第 7 部分:区域感知格式化

DateFormatter

let formatter = DateFormatter()
formatter.locale = Locale.current  // ✅ 使用当前区域
formatter.dateStyle = .long
formatter.timeStyle = .short

let dateString = formatter.string(from: Date())

// 美国:"January 15, 2024 at 3:30 PM"
// 法国:"15 janvier 2024 à 15:30"
// 日本:"2024年1月15日 15:30"

切勿硬编码日期格式字符串:

// ❌ 错误 - 在其他区域会出错
formatter.dateFormat = "MM/dd/yyyy"

// ✅ 正确 - 适应区域
formatter.dateStyle = .short

用于货币的 NumberFormatter

let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .currency

let priceString = formatter.string(from: 29.99)

// 美国:"$29.99"
// 英国:"£29.99"
// 日本:"¥30"(四舍五入为整数)
// 法国:"29,99 €"(逗号小数点,符号前有空格)

MeasurementFormatter

let distance = Measurement(value: 100, unit: UnitLength.meters)

let formatter = MeasurementFormatter()
formatter.locale = Locale.current

let distanceString = formatter.string(from: distance)

// 美国:"328 ft"(转换为英制)
// 公制国家:"100 m"

区域特定排序

let names = ["Ångström", "Zebra", "Apple"]

// ✅ 区域感知排序
let sorted = names.sorted { (lhs, rhs) in
    lhs.localizedStandardCompare(rhs) == .orderedAscending
}

// 瑞典:["Ångström", "Apple", "Zebra"]  (Å 在瑞典语中排在首位)
// 美国:["Ångström", "Apple", "Zebra"]      (Å 被视为 A)

第 8 部分:App Shortcuts 本地化

带参数的短语

import AppIntents

struct ShowTopDonutsIntent: AppIntent {
    static var title: LocalizedStringResource = "显示热门甜甜圈"

    @Parameter(title: "时间范围")
    var timeframe: Timeframe

    static var parameterSummary: some ParameterSummary {
        Summary("\(.applicationName) 的趋势,时间范围 \(.$timeframe)") {
            \.$timeframe
        }
    }
}

字符串目录生成:Xcode 会自动为 App Shortcuts 短语生成条目,包括带标记(如 \(.applicationName) 和 \(.$timeframe))的参数化短语。

短语中的标记

Summary("在 \(.applicationName) 中查找 \(.$donutName) 甜甜圈")

字符串目录中的条目:

{
  "在 %@ 中查找 %@ 甜甜圈" : {
    "comment" : "...",
    "localizations" : {
      "es" : {
        "stringUnit" : {
          "value" : "Buscar donas %2$@ en %1$@"
        }
      }
    }
  }
}

第 9 部分:从传统格式迁移

.strings 到 .xcstrings

迁移工具(Xcode 15+):

  1. 在 Xcode 中打开项目
  2. 选择项目导航器中的 .strings 文件
  3. 编辑器 → 迁移到字符串目录

手动迁移:

// 旧的 .strings 文件(已迁移)
"Welcome" = "Welcome";
"Goodbye" = "Goodbye";
// 新的 .xcstrings 条目
{
  "Welcome" : {
    "comment" : "应用启动时的问候语"
  },
  "Goodbye" : {
    "comment" : "应用关闭时的告别语"
  }
}

.stringsdict 到 .xcstrings

// 旧的 .stringsdict 复数
{
  "%d items" : {
    "NSStringLocalizedFormatKey" : "%#@items@",
    "items" : {
      "one" : "%d item",
      "other" : "%d items"
    }
  }
}
// 新的 .xcstrings 复数(自动)
{
  "%d items" : {
    "comment" : "购物车中的物品数量"
  }
}

只需在 Swift 代码中使用字符串,Xcode 会自动检测复数形式并为你创建变体。

版本检查

#if compiler(>=6.0)
// 使用 String Catalog API(需要 Swift 6/Xcode 16+)
#else
// 使用后备方案
#endif

第 10 部分:高级功能

自动符号生成(Xcode 26+)

// Xcode 26 可以从字符串目录自动生成类型安全符号
// 启用:构建设置 → 本地化符号生成 → 是

// 用法(无需手动定义键)
Text(\.welcomeMessage)

// 如果键不存在,编译器会报错

#bundle 宏(Xcode 26+)

// 用法
let localize = #bundle("MyFeature")

Text(localize("welcomeMessage"))

AI 驱动的注释生成(Xcode 26+)

// 可选:启用 AI 注释生成
// Xcode 可以分析代码并为翻译人员生成有意义的注释

本地化调试

Xcode 编辑器:

  • 字符串目录编辑器显示每个字符串的状态
  • 单击“在源代码中显示”找到使用该字符串的位置

运行时:

// 在 SwiftUI 预览中测试
struct MyView_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
            .environment(\.locale, .init(identifier: "es"))
    }
}

// 在代码中检查
let isRTL = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft

常见问题排查

问题解决方案
未提取字符串检查构建设置中启用了编译器提取
复数形式不生效确保字符串包含 %lld 或 %d 格式化说明符
RTL 镜像未发生使用 .leading/.trailing 而非 .left/.right
符号未生成(Xcode 26)在构建设置中启用本地化符号生成

附录:区域代码

语言区域代码复数形式RTL
英语 (美国)en-USone, other否
中文 (简体)zh-Hansother否
中文 (繁体)zh-Hantother否
西班牙语esone, many, other否
阿拉伯语arzero, one, two, few, many, other是
希伯来语heone, two, many, other是
日语jaother否
韩语koother否
法语frone, many, other否
德语deone, other否
俄语ruone, few, many, other否
波兰语plone, few, many, other否

另请参阅

  • WWDC 2023:探索字符串目录 (10155)
  • WWDC 2022:SwiftUI 中的本地化
  • 苹果人机界面指南:本地化
  • NSLocalizedString 文档

Individual skills in this repo

This repo contains 7 individual skills — each has its own dedicated page.

IGTA-Tech/claude-skills-research

Use when implementing SwiftUI animations, understanding VectorArithmetic, using @Animatable macro, choosing between spring and timing curve animations, or debugging animation behavior - comprehensive animation reference from iOS 13 through iOS 26

IGTA-Tech/claude-skills-research

Use when CAAnimation completion handler doesn't fire, spring physics look wrong on device, animation duration mismatches actual time, gesture + animation interaction causes jank, or timing differs between simulator and real hardware - systematic CAAnimation diagnosis with CATransaction patterns, frame rate awareness, and device-specific behavior

IGTA-Tech/claude-skills-research

This skill should be used when comparing two videos to analyze compression results or quality differences. Generates interactive HTML reports with quality metrics (PSNR, SSIM) and frame-by-frame visual comparisons. Triggers when users mention "compare videos", "video quality", "compression analysis", "before/after compression", or request quality assessment of compressed videos.

IGTA-Tech/claude-skills-research

Download YouTube videos and HLS streams (m3u8) from platforms like Mux, Vimeo, etc. using yt-dlp and ffmpeg. Use this skill when users request downloading videos, extracting audio, handling protected streams with authentication headers, or troubleshooting download issues like nsig extraction failures, 403 errors, or cookie extraction problems.

IGTA-Tech/claude-skills-research

Write high-converting landing page copy using proven frameworks like PAS (Problem-Agitate-Solution), AIDA, and StoryBrand. Creates headlines, value propositions, CTAs, and full page sections optimized for conversion. Use when users need landing page copy, sales page content, or marketing website text.

IGTA-Tech/claude-skills-research

Downloads videos from YouTube and other platforms for offline viewing, editing, or archival. Handles various formats and quality options.

IGTA-Tech/claude-skills-research

Download YouTube video transcripts when user provides a YouTube URL or asks to download/get/fetch a transcript from YouTube. Also use when user wants to transcribe or get captions/subtitles from a YouTube video.

相关技能