本地化與國際化
使用 String Catalogs 進行應用程式本地化的全面指南。Apple Design Award 包容性得獎者總是支援多種語言,並提供出色的 RTL(從右至左)支援。
概述
String Catalogs(.xcstrings)是 Xcode 15 用於管理應用程式本地化的統一格式。它們以單一基於 JSON 的格式取代了舊版的 .strings 和 .stringsdict 檔案,這種格式更易於維護、差異比對,並與翻譯工作流程整合。
此技能涵蓋 String Catalogs、SwiftUI/UIKit 本地化 API、複數處理、RTL 支援、語言環境感知格式化,以及從舊版格式遷移的策略。
何時使用此技能
- 在 Xcode 15+ 中設定 String Catalogs
- 本地化 SwiftUI 和 UIKit 應用程式
- 正確處理複數形式(對許多語言至關重要)
- 支援 RTL 語言(阿拉伯語、希伯來語)
- 根據語言環境格式化日期、數字和貨幣
- 從舊版
.strings/.stringsdict檔案遷移 - 準備 App Shortcuts 和 App Intents 以供本地化
- 除錯遺失的翻譯或不正確的複數形式
系統需求
- Xcode 15+ 用於 String Catalogs(
.xcstrings) - Xcode 26+ 用於自動符號生成、
#bundle巨集和 AI 驅動的註解生成 - iOS 15+ 用於
LocalizedStringResource - iOS 16+ 用於 App Shortcuts 本地化
- 較早的 iOS 版本使用舊版
.strings檔案
第 1 部分:String Catalogs(WWDC 2023/10155)
建立 String Catalog
方法 1:Xcode 導覽器
- 檔案 → 新增 → 檔案
- 選擇「String Catalog」
- 命名(例如
Localizable.xcstrings) - 加入目標
方法 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(🔴)- 原始碼中已找不到該字串
工作流程:
- 開發者新增字串 → New
- 翻譯人員加入翻譯 → Reviewed
- 開發者變更原始碼 → Needs Review
- 翻譯人員更新 → Reviewed
- 開發者移除程式碼 → Stale
第 2 部分:SwiftUI 本地化
LocalizedStringKey(自動)
使用 String 參數的 SwiftUI 視圖會自動支援本地化:
// ✅ 可自動本地化
Text("Welcome to WWDC!")
Label("Thanks for shopping with us!", systemImage: "bag")
Button("Checkout") { }
// Xcode 會將這些字串萃取至 String Catalog
運作方式:SwiftUI 在內部使用 LocalizedStringKey,它會在 String Catalogs 中查找字串。
附帶註解的 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")
// 使用預設值(Key ≠ 英文字串)
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")
第 3 部分: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 本地化
本地化應用程式名稱、權限等:
- 選取
Info.plist - Editor → Add Localization
- 為每種語言建立
InfoPlist.strings:
// InfoPlist.strings (Spanish)
"CFBundleName" = "Mi Aplicación";
"NSCameraUsageDescription" = "La app necesita acceso a la cámara para tomar fotos.";
第 4 部分:複數化
不同語言有不同的複數規則:
- 英語: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 匯出格式
在匯出以供翻譯時(File → Export Localizations):
舊版(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, otheralbumCount:one, other- 總組合數:2 × 2 = 4 個翻譯條目
第 5 部分:裝置與寬度變體
裝置特定字串
不同平台使用不同文字:
// 相同程式碼,不同裝置使用不同字串
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 可以在窄寬度下提供較短的文字。
第 6 部分:RTL 支援
佈局鏡像
SwiftUI 會自動為 RTL 語言鏡像佈局:
// ✅ 會自動為阿拉伯語/希伯來語鏡像
HStack {
Image(systemName: "chevron.right")
Text("Next")
}
// iPhone (English): [>] Next
// iPhone (Arabic): 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 Scheme:
- Edit Scheme → Run → Options
- Application Language:Arabic / Hebrew
- 或者:App Language → Right-to-Left Pseudolanguage
模擬器: Settings → General → Language & Region → Preferred Language Order
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 = "Show Top Donuts"
@Parameter(title: "Timeframe")
var timeframe: Timeframe
static var parameterSummary: some ParameterSummary {
Summary("\(.applicationName) Trends for \(\.$timeframe)") {
\.$timeframe
}
}
}
String Catalog 會自動萃取:
- Intent 標題
- 參數名稱
- 帶有佔位符的片語模板
本地化片語:
English: "Food Truck Trends for this week"
Spanish: "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..."
],
shortTitle: "Trends",
systemImageName: "chart.line.uptrend.xyaxis"
)
}
}
第 9 部分:從舊版檔案遷移
從 .strings 遷移
Step 1:在 Xcode 中建立 String Catalog
Step 2:手動導入
從舊版 .strings 檔案複製鍵/值對,或使用遷移工具。
Step 3:驗證:
- 所有鍵都正確出現?
- 「New」狀態表示已成功萃取?
- Xcode 是否報告缺少鍵的警告?
從 .stringsdict 遷移
.stringsdict 格式:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>%lld Recent Visitors</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@recentVisitors@</string>
<key>recentVisitors</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>one</key>
<string>%lld Recent Visitor</string>
<key>other</key>
<string>%lld Recent Visitors</string>
</dict>
</dict>
</dict>
</plist>
逐步遷移到 String Catalog:
- 建立 String Catalog(如果尚未存在)
- 在 Xcode 15+ 開啟 String Catalog
- 將同樣的字串鍵加入原始碼
- Xcode 會填入變體,但您需要手動驗證
指令稿遷移範例(Python):
import plistlib
import json
def stringsdict_to_xcstrings(stringsdict_path, output_path):
with open(stringsdict_path, 'rb') as f:
data = plistlib.load(f)
xcstrings = {
"sourceLanguage": "en",
"strings": {},
"version": "1.0"
}
for key, value in data.items():
entry = {
"localizations": {
"en": {
"variations": {}
}
}
}
if isinstance(value, dict) and 'NSStringLocalizedFormatKey' in value:
# 處理複數
plural_variations = {}
for plural_key in ['zero', 'one', 'two', 'few', 'many', 'other']:
if plural_key in value:
plural_variations[plural_key] = {
"stringUnit": {
"state": "translated",
"value": value[plural_key]
}
}
entry["localizations"]["en"]["variations"]["plural"] = plural_variations
else:
# 處理一般字串
entry["localizations"]["en"] = {
"stringUnit": {
"state": "translated",
"value": value
}
}
xcstrings["strings"][key] = entry
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(xcstrings, f, indent=2, ensure_ascii=False)
第 10 部分:Xcode 26+ 的新功能
Xcode 26 引入了強大的本地化改進:
自動符號生成
String Catalogs 現在會自動為翻譯生成型別安全的符號,消除對字串鍵的猜測,並提供編譯器檢查的可發現性。
#bundle 巨集
新的 #bundle 巨集簡化了處理不同套件的字串表格,使框架和套件管理器的本地化更簡潔。
AI 驅動的註解生成
Xcode 26 使用機器學習自動為新字串生成註解,無需手動輸入即可提供翻譯人員上下文。這基於字串的上下文和 Apple 對應用程式 UI 模式的理解。
第 11 部分:除錯與驗證
使用偽語言進行測試
Xcode 提供偽語言來在開發期間測試本地化:
- Edit Scheme → Run → Options
- App Language:選擇「Double-Length Pseudolanguage」
- 這會加倍字串長度以測試佈局問題
還有「Right-to-Left Pseudolanguage」用於 RTL 測試。
常見問題
字串未在 String Catalog 中顯示:
- 檢查是否在建置設定中啟用了萃取
- 確保字串是字面量,而非變數
- 驗證字串格式:
Text("Hello")✅ vsText(myVariable)❌
複數形式錯誤:
- 確認您已為相關語言提供所有必要形式
- 使用
%lld格式指定器 - 在模擬器中用多種語言測試
RTL 佈局中斷:
- 搜尋硬編碼的
.leading/.trailing替代為.left/.right - 檢查自訂圖片是否正確翻轉
- 使用 SwiftUI 預覽進行 RTL 測試
附錄:語言代碼參考
| 語言 | 地區代碼 | 複數形式 | RTL |
|---|---|---|---|
| 英語(美國) | en-US | one, other | 否 |
| 西班牙語 | es | one, other | 否 |
| 法語 | fr | one, other | 否 |
| 德語 | de | one, other | 否 |
| 義大利語 | it | one, other | 否 |
| 葡萄牙語(巴西) | pt-BR | one, other | 否 |
| 俄語 | ru | one, few, many | 否 |
| 波蘭語 | pl | one, few, other | 否 |
| 阿拉伯語 | ar | zero, one, two, few, many, other | 是 |
| 希伯來語 | he | one, other | 是 |
| 日語 | ja | other | 否 |
| 中文(簡體) | zh-Hans | other | 否 |
| 中文(繁體) | zh-Hant | other | 否 |
| 韓語 | ko | other | 否 |
更多資源
- WWDC 2023:本地化從 String Catalogs 開始
- WWDC 2023:探索 App Shortcuts 的本地化
- Apple 文件:String Catalogs
- Apple 文件:國際化與本地化指南
由 ComeOnOliver/skillshub 提供 · 在 Xcode 15-26 中提供全面的 i18n 模式