| 策略 | 描述 | 適用場景 |
|---|---|---|
| 用戶手動切換 | App 內提供語言選單,強制切換 | 跨國團隊內部工具、特定業務需求 |
| 跟隨系統語言 (推薦) | 自動讀取 `[NSLocale preferredLanguages]` 切換 | 面向大眾的商業 App、符合平台規範 |
本文聚焦 **系統語言跟隨模式** 的標準實現流程。
Project/ ├── en.lproj/ # 英文 (基準語言) │ ├── Localizable.strings │ ├── InfoPlist.strings │ └── Main.strings (Storyboard/XIB) ├── zh-Hans.lproj/ # 簡體中文 │ ├── Localizable.strings │ ├── InfoPlist.strings │ └── Main.strings ├── zh-Hant.lproj/ # 繁體中文 ├── ja.lproj/ # 日文 └── ...
// InfoPlist.strings (English)
CFBundleDisplayName = "MyApp";
// InfoPlist.strings (Chinese)
CFBundleDisplayName = "我的應用";
// Localizable.strings (English)
"welcome" = "Welcome to MyApp!";
"login.button" = "Login";
"error.network" = "Network error, please retry.";
// Localizable.strings (Chinese)
"welcome" = "歡迎使用我的應用!";
"login.button" = "登入";
"error.network" = "網路錯誤,請重試。";
NSLog(@"%@", NSLocalizedString(@"welcome", nil));
// 或帶註釋給翻譯參考
NSLog(@"%@", NSLocalizedString(@"login.button", @"登入按鈕標題"));
// 自定義表名 (非 Localizable.strings)
NSLocalizedStringFromTable(@"key", @"MyCustomTable", nil);
方法 A:字串映射法(靈活、不改檔名)
// Localizable.strings
"logo.image" = "logo_en.png"; // English
"logo.image" = "logo_cn.png"; // Chinese
// 代碼
UIImage *logo = [UIImage imageNamed:NSLocalizedString(@"logo.image", nil)];
方法 B:資源檔案本地化(官方標準、Xcode 管理)
推薦方法 B:Xcode 統一管理、編譯期優化、無字串鍵值維護成本。
同圖片方法 B:選中檔案 → Localization 添加語言 → 各語言目錄下替換內容。
// 強制切換語言 (需重啟或手動刷新 UI)
[[NSUserDefaults standardUserDefaults] setObject:@[@"zh-Hans", @"en"] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
// 提示用戶重啟 App
不重啟刷新:需手動遍歷視圖重新賦值 `NSLocalizedString`,或用 `NSNotificationCenter` 通知所有視圖更新。
針對「1 條消息 / 3 條消息」等複數規則:
// Localizable.stringsdict (Property List 格式)
messages.count
NSStringLocalizedFormatKey
%#@count@
count
NSStringFormatSpecTypeKey
NSStringFormatSpecTypeKey
NSStringFormatValueTypeKey
d
zero
無消息
one
%d 條消息
other
%d 條消息
NSString *fmt = NSLocalizedString(@"messages.count", nil);
NSString *result = [NSString stringWithFormat:fmt, count];
// count=0 → "無消息", count=1 → "1 條消息", count=5 → "5 條消息"