Communitygithub.com

ComeOnOliver/skillshub

在本地化应用、使用 String Catalog、生成类型安全符号(Xcode 26+)、处理复数、RTL 布局、地区感知格式化或从 .strings 文件迁移时使用——适用于 Xcode 15-26 的全面 i18n 模式

skillshub 是什么?

该技能是一份全面的应用本地化指南,重点介绍 Xcode 15 引入的 String Catalog(.xcstrings)格式,它替代了传统的 .strings 和 .stringsdict 文件,采用统一的 JSON 格式,便于维护和集成翻译工作流。技能覆盖 SwiftUI 和 UIKit 的本地化 API,包括自动本地化(LocalizedStringKey)、显式本地化(String(localized:))以及延迟本地化(LocalizedStringResource),并深入探讨了复数处理(涵盖英语、俄语、阿拉伯语等多种语言规则)、RTL 布局支持(阿拉伯语、希伯来语)以及设备特定的文本变体。此外,还包含地区感知的日期、数字和货币格式化,App Shortcuts 本地化,以及从旧格式迁移的策略。支持 Xcode 15-26 和 iOS 15+,Xcode 26+ 提供自动符号生成、#bundle 宏和 AI 注释生成等高级功能。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-localization

在你喜欢的 AI 中提问

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

文档

本地化与国际化 (Localization & Internationalization)

使用 String Catalog 进行应用本地化的全面指南。苹果设计奖包容性获奖者始终支持多种语言并提供出色的 RTL(从右到左)支持。

概述

String Catalog(.xcstrings)是 Xcode 15 引入的统一格式,用于管理应用本地化。它用基于 JSON 的单一格式取代了传统的 .strings 和 .stringsdict 文件,更易于维护、对比和集成翻译工作流。

本技能涵盖 String Catalog、SwiftUI/UIKit 本地化 API、复数处理、RTL 支持、地区感知格式化以及从旧格式迁移的策略。

何时使用本技能

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

系统要求

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

第一部分:String Catalog(WWDC 2023/10155)

创建 String Catalog

方法 1:Xcode 导航器

  1. 文件 → 新建 → 文件
  2. 选择“String Catalog”
  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 短语

需要的构建设置:

  • “Use Compiler to Extract Swift Strings” → 是
  • “Localization Prefers String Catalogs” → 是

String Catalog 结构

每个条目包含:

  • 键(Key):唯一标识符(默认:英文字符串)
  • 默认值(Default Value):翻译缺失时的回退值
  • 注释(Comment):为翻译人员提供的上下文
  • 字符串表(String Table):组织容器(默认:“Localizable”)

.xcstrings JSON 示例:

{
  "sourceLanguage" : "en",
  "strings" : {
    "Thanks for shopping with us!" : {
      "comment" : "Label above checkout button",
      "localizations" : {
        "en" : {
          "stringUnit" : {
            "state" : "translated",
            "value" : "Thanks for shopping with us!"
          }
        },
        "es" : {
          "stringUnit" : {
            "state" : "translated",
            "value" : "¡Gracias por comprar con nosotros!"
          }
        }
      }
    }
  },
  "version" : "1.0"
}

翻译状态

Xcode 会跟踪每个翻译的状态:

  • 新建(New)(⚪)— 字符串尚未翻译
  • 需要审阅(Needs Review)(🟡)— 源文本已更改,翻译可能已过时
  • 已审阅(Reviewed)(✅)— 翻译已批准且为最新
  • 过期(Stale)(🔴)— 字符串在源代码中不再找到

工作流程:

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

第二部分:SwiftUI 本地化

LocalizedStringKey(自动)

接受 String 参数的 SwiftUI 视图自动支持本地化:

// ✅ 自动可本地化
Text("Welcome to WWDC!")
Label("Thanks for shopping with us!", systemImage: "bag")
Button("Checkout") { }

// Xcode 将这些字符串提取到 String Catalog

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

带注释的 String(localized:)

在 Swift 代码中显式本地化:

// 基本用法
let title = String(localized: "Welcome to WWDC!")

// 为翻译人员提供注释
let title = String(localized: "Welcome to WWDC!",
                   comment: "Notification banner title")

// 自定义表
let title = String(localized: "Welcome to WWDC!",
                   table: "WWDCNotifications",
                   comment: "Notification banner title")

// 使用默认值(键 ≠ 英文字符串)
let title = String(localized: "WWDC_NOTIFICATION_TITLE",
                   defaultValue: "Welcome to WWDC!",
                   comment: "Notification banner title")

最佳实践:始终包含 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: "Recent Purchases",
    subtitle: "Items you've ordered in the past week."
)

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

带 Markdown 的 AttributedString

// Markdown 格式在不同本地化中保持不变
let subtitle = AttributedString(localized: "**Bold** and _italic_ text")

第三部分:UIKit 与 Foundation

NSLocalizedString 宏

// 基本用法
let title = NSLocalizedString("Recent Purchases", comment: "Button Title")

// 带表
let title = NSLocalizedString("Recent Purchases",
                             tableName: "Shopping",
                             comment: "Button Title")

// 带 bundle
let title = NSLocalizedString("Recent Purchases",
                             tableName: nil,
                             bundle: .main,
                             value: "",
                             comment: "Button Title")

Bundle.localizedString

let customBundle = Bundle(for: MyFramework.self)
let text = customBundle.localizedString(forKey: "Welcome",
                                        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" = "Mi Aplicación";
"NSCameraUsageDescription" = "La app necesita acceso a la cámara para tomar fotos.";

第四部分:复数处理

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

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

SwiftUI 复数处理

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

// 自定义格式化
Text("\(visitorCount) Recent Visitors")

在 String Catalog 中:

{
  "strings" : {
    "%lld Recent Visitors" : {
      "localizations" : {
        "en" : {
          "variations" : {
            "plural" : {
              "one" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "%lld Recent Visitor"
                }
              },
              "other" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "%lld Recent Visitors"
                }
              }
            }
          }
        }
      }
    }
  }
}

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>

String Catalog(更清晰):

<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) songs on \(albumCount) albums")

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

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

第五部分:设备与宽度变体

设备特定字符串

不同平台使用不同的文本:

// 相同的代码,不同设备显示不同字符串
Text("Bird Food Shop")

String Catalog 变体:

{
  "Bird Food Shop" : {
    "localizations" : {
      "en" : {
        "variations" : {
          "device" : {
            "applewatch" : {
              "stringUnit" : {
                "value" : "Bird Food"
              }
            },
            "other" : {
              "stringUnit" : {
                "value" : "Bird Food Shop"
              }
            }
          }
        }
      }
    }
  }
}

结果:

  • iPhone/iPad:"Bird Food Shop"
  • Apple Watch:"Bird Food"(小屏幕使用较短文本)

宽度变体

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

Text("Application Settings")

String Catalog 可以为窄宽度提供更短的文本。


第六部分:RTL 支持

布局镜像

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

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

// iPhone(英语):[>] Next
// iPhone(阿拉伯语):Next [<]

使用 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"))
    }
}

第七部分:地区感知格式化

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)

第八部分:App Shortcuts 本地化

带参数的短语

import AppIntents

struct ShowTopDonutsIntent: AppIntent {
    static var title: LocalizedStringResource = "Show Top Donuts"

    @Parameter(title: "Timeframe")
    var timeframe: Timeframe

    static var parameterSummary: some ParameterSummary {
        Summary("\.applicationName) Trends for \(\.$timeframe)") {
            \.$timeframe)
        }
    }
}

String Catalog 自动提取:

  • 意图标题
  • 参数名称
  • 包含占位符的短语模板

本地化短语:

英语:"Food Truck Trends for this week"
西班牙语:"Tendencias de Food Truck para esta semana"

AppShortcutsProvider 本地化

struct FoodTruckShortcuts: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(
            intent: ShowTopDonutsIntent(),
            phrases: [
                "\.applicationName) Trends for \(\.$timeframe)",
                "Show Trending Donuts",
                "Popular donuts this \(\.$timeframe)"
            ],
            shortTitle: "Donut Trends",
            systemImageName: "chart.bar"
        )
    }
}

第九部分:迁移策略

从 .strings 迁移

手动迁移:

  1. 在 Xcode 中创建新的 String Catalog
  2. 从旧的 .strings 文件中复制键和值
  3. 将 formatSpec 转换为 String Catalog 的复数变体

Xcode 自动迁移:

  1. 选择项目导航器中的 .strings 文件
  2. 编辑器 → 迁移到 String Catalog

迁移清单:

  • 更新构建设置:“Localization Prefers String Catalogs” → 是
  • 验证复数形式是否正确迁移
  • 删除旧的 .strings 和 .stringsdict 文件
  • 测试所有语言的回退逻辑

字符串键的最佳实践

场景推荐避免
短标签使用英文字符串使用像 label_1 这样的抽象键
带上下文的键键 = 英语,添加注释依赖开发者记忆
动态内容使用 String(localized:) 或 AttributedString拼接预翻译的字符串
复数字符串使用 Text 插值 \(count) items手动构建复数字符串

问题排查

常见问题

  1. 字符串未出现在 String Catalog 中

    • 确认在要编译的 Swift/ObjC 文件中
    • 确保编译器提取设置已启用
    • 尝试产品 → 清理构建文件夹
  2. 复数形式不正确

    • 检查 String Catalog 中的复数变体
    • 使用正确的格式说明符('lld、'ld)
    • 验证语言有正确的变体数量
  3. RTL 布局问题

    • 使用 .leading/.trailing 而非 .left/.right
    • 标记不应翻转的图片
    • 使用 RTL 伪语言测试
  4. 从错误表加载字符串

    • 指定正确的 table 参数
    • 验证 .xcstrings 中的表名
    • 使用 Bundle.localizedString 获取细致控制

关键要点

  1. 使用 String Catalogs(Xcode 15+)— 它们是更清洁、更易于维护的格式
  2. 始终提供注释 — 翻译人员需要上下文才能翻译好
  3. 永远不要硬编码格式 — 使用系统格式化器,它们会自动适应地区
  4. 使用语义布局 — .leading/.trailing 是 RTL 安全的关键
  5. 正确测试复数 — 每种语言都有自己的规则
  6. 从第一天起就本地化 — 后期添加本地化要困难得多
  7. 使用 LocalizedStringResource 实现可重用的本地化组件

Individual skills in this repo

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

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能