Communitygithub.com

本地化與國際化 (Localization & Internationalization)

使用字串目錄 (String Catalogs) 本地化應用程式、產生型別安全的符號 (Xcode 26+)、處理複數、RTL 佈局、以及區域感知格式化等完整的 i18n 模式,支援 Xcode 15-26。

本地化與國際化 (Localization & Internationalization) 是什麼?

此技能提供了一個全面的指南,用於在 Apple 生態系統中進行應用程式本地化,特別著重於 Xcode 15 引入的 String Catalogs (.xcstrings)。它涵蓋了從 SwiftUI 和 UIKit 的本地化 APIs、複數形式的正確處理(對於俄語、阿拉伯語等語言至關重要)、到右至左 (RTL) 佈局支援和區域感知格式化(在日期、貨幣和測量單位中)的所有內容。它還包括從傳統的 `.strings` 和 `.stringsdict` 檔案遷移的詳細策略,以及在 App Shortcuts 和 App Intents 中準備本地化字串的指引。該指南明確列出了不同功能所要求的系統版本(例如,Xcode 15+ 用於 String Catalogs,Xcode 26+ 用於自動符號生成),並包含豐富的程式碼範例,展示如何在實作中最佳化其國際化工作流程。

相容平台✓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 用來管理應用程式在地化的統一格式。它取代了傳統的 .strings 和 .stringsdict 檔案,採用單一基於 JSON 的格式,更容易維護、比對差異,以及與翻譯工作流程整合。

本技能涵蓋字串目錄、SwiftUI/UIKit 在地化 API、複數處理、RTL 支援、區域感知格式化,以及從傳統格式遷移的策略。

何時使用此技能

  • 在 Xcode 15+ 中設定字串目錄
  • 對 SwiftUI 和 UIKit 應用程式進行在地化
  • 正確處理複數形式(對許多語言至關重要)
  • 支援 RTL 語言(阿拉伯語、希伯來語)
  • 根據區域格式化日期、數字和貨幣
  • 從傳統的 .strings/.stringsdict 檔案遷移
  • 準備應用程式捷徑和應用程式意圖以進行在地化
  • 偵錯遺漏的翻譯或不正確的複數形式

系統需求

  • Xcode 15+:用於字串目錄 (.xcstrings)
  • Xcode 26+:用於自動符號生成、#bundle 巨集和 AI 驅動的註解生成
  • iOS 15+:用於 LocalizedStringResource
  • iOS 16+:用於應用程式捷徑在地化
  • 較早的 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 值
  • 應用程式捷徑片語

需要設定的建置設定:

  • 「使用編譯器萃取 Swift 字串」 → 是
  • 「在地化偏好字串目錄」 → 是

字串目錄結構

每個條目包含:

  • 索引鍵:唯一識別碼(預設是英文原文)
  • 預設值:若缺少翻譯時的回退值
  • 註解:提供翻譯人員上下文
  • 字串表格:組織容器(預設為「Localizable」)

.xcstrings JSON 範例:

{
  "sourceLanguage" : "en",
  "strings" : {
    "Thanks for shopping with us!" : {
      "comment" : "結帳按鈕上方的標籤",
      "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 會追蹤每個翻譯的狀態:

  • 新增 (⚪) - 字串尚未翻譯
  • 需要審閱 (🟡) - 來源已變更,翻譯可能已過時
  • 已審閱 (✅) - 翻譯已核准且為最新
  • 過時 (🔴) - 原始碼中已找不到此字串

工作流程:

  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" = "Mi Aplicación";
"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 位最近訪客"
                }
              },
              "other" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "%lld 位最近訪客"
                }
              }
            }
          }
        }
      }
    }
  }
}

XLIFF 匯出格式

匯出以供翻譯時(檔案 → 匯出在地化):

傳統格式 (stringsdict):

<trans-unit id="/%lld 位最近訪客:dict/NSStringLocalizedFormatKey:dict/:string">
    <source>%#@recentVisitors@</source>
</trans-unit>

<trans-unit id="/%lld 位最近訪客:dict/recentVisitors:dict/one:dict/:string">
    <source>%lld 位最近訪客</source>
    <target>%lld Visitante Recente</target>
</trans-unit>

字串目錄(更簡潔):

<trans-unit id="%lld 位最近訪客|==|plural.one">
    <source>%lld 位最近訪客</source>
    <target>%lld Visitante Recente</target>
</trans-unit>

<trans-unit id="%lld 位最近訪客|==|plural.other">
    <source>%lld 位最近訪客</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 (阿拉伯文):下一步 [<]

使用前導/尾隨而非左/右

始終使用語義方向:

// ✅ 正確 - 會自動鏡像
.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 Scheme:

  1. 編輯 Scheme → 執行 → 選項
  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())

// 美國:「2024年1月15日 下午3:30」
// 法國:「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 部分:應用程式捷徑在地化

帶有參數的片語

import AppIntents

struct ShowTopDonutsIntent: AppIntent {
    static var title: LocalizedStringResource = "顯示最佳甜甜圈"

    @Parameter(title: "時間範圍")
    var timeframe: Timeframe

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

字串目錄將包含如 "Display best donuts in {timeframe}" 的項目,以及為每個參數產生的片語。


第 9 部分:遷移策略

從 .strings 遷移

逐步遷移:

  1. 匯出現有翻譯:

    • 編輯器 → 匯出在地化 → 全部
    • 儲存 XLIFF 檔案
  2. 建立字串目錄:

    • 檔案 → 新增 → 字串目錄
    • 命名為 Localizable.xcstrings
  3. 匯入 XLIFF:

    • 在 Navigator 中選取 Localizable.xcstrings
    • 編輯器 → 匯入在地化
    • 選取您的 XLIFF 檔案

混合方法(逐個檔案):

您可以在轉換過程中同時使用 .strings 和 .xcstrings 檔案:

📁 Project/
  ├── Localizable.xcstrings      # 新的字串
  ├── en.lproj/
  │   ├── Localizable.strings    # 仍在使用的舊字串
  │   └── InfoPlist.strings
  └── es.lproj/
      ├── Localizable.strings
      └── InfoPlist.strings

將一個字串表格遷移到字串目錄:

// 仍然可以從 .strings 檔案參考
let oldTitle = NSLocalizedString("old_key", tableName: "OldStrings", comment: "舊格式")

// 同時使用新的 .xcstrings
let newTitle = String(localized: "新金鑰")

從 stringsdict 遷移(複數)

Xcode 會在建立字串目錄時自動轉換 stringsdict 中的複數規則。驗證轉換:

  1. 在字串目錄中找到複數字串
  2. 展開「變體」部分
  3. 確認所有複數形式(one, few, many 等)都已正確遷移

第 10 部分:Xcode 26+ 新功能

自動符號生成 (Xcode 26+)

Xcode 26+ 可以從您的字串目錄自動生成型別安全的符號:

// Xcode 26 從 Localizable.xcstrings 生成
let greeting = String(localized: "歡迎")
let title = String(localized: "設定")

運作方式:

  • 編譯器會掃描您的字串目錄
  • 為任何用於 String(localized:) 或 SwiftUI 檢視的索引鍵生成型別安全的符號
  • 如果使用了未定義的索引鍵,會產生編譯錯誤

這意味著:您再也不會因為打字錯誤而遺失索引鍵了!

#bundle 巨集 (Xcode 26+)

明確指定要使用的 bundle:

// 從特定框架的目錄載入字串
let frameworkString = String(localized: "框架金鑰", bundle: #bundle("MyFramework"))

AI 驅動的註解生成 (Xcode 26+)

Xcode 26 可以自動為您的字串目錄生成有意義的註解:

  1. 在字串目錄中選取一個字串
  2. 編輯器 → 生成註解
  3. Xcode 會分析使用情況並建議上下文

附錄 A:常見字串目錄結構

最簡配置

{
  "sourceLanguage" : "en",
  "strings" : {},
  "version" : "1.0"
}

一個字串,一種語言

{
  "sourceLanguage" : "en",
  "strings" : {
    "設定" : {
      "extractionState" : "extracted_with_value",
      "localizations" : {
        "zh-Hans" : {
          "stringUnit" : {
            "state" : "translated",
            "value" : "設定"
          }
        }
      }
    }
  },
  "version" : "1.0"
}

帶有裝置變體的字串

{
  "sourceLanguage" : "en",
  "strings" : {
    "購物車" : {
      "localizations" : {
        "en" : {
          "variations" : {
            "device" : {
              "applewatch" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "購物車"
                }
              },
              "ipad" : {
                "stringUnit" : {
                  "state" : "translated",
                  "value" : "購物車"
                }
              }
            }
          }
        }
      }
    }
  },
  "version" : "1.0"
}

附錄 B:常見陷阱

避免的錯誤

  1. ❌ 缺少註解

    • 永遠提供 comment 參數
    • 否則翻譯人員不知道上下文
  2. ❌ 字串串接

    // 錯誤 - 無法進行在地化,因為單字順序不同
    let message = "歡迎, " + userName + "!"
    
    // 正確 - 使用字串插值
    let message = String(localized: "歡迎, \(userName)!")
    
  3. ❌ 使用 .strings 檔案

    • 如果已使用 .strings,請遷移到 .xcstrings
    • .strings 檔案不易於審查差異
  4. ❌ 硬編碼區域

    // 錯誤 - 忽略使用者設定
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US")
    
    // 正確 - 尊重使用者偏好
    let formatter = DateFormatter()
    formatter.locale = Locale.current
    

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.

相關技能