
无论是 国际化(i18n) 还是 本地化(l10n),对于出海的 App 来说,多语言适配都是绕不过去的一环。本文将带你从最基础的 .strings 到新一代的 .xcstrings,再到 UIKit 和 SwiftUI 的具体实现,一步步梳理清楚。
1. iOS 多语言适配的文件体系
在 iOS 项目中,多语言通常依赖以下几类文件:
| 文件类型 | 说明 | 示例 |
|---|---|---|
| .strings | 最常见,键值对形式存放翻译 | Localizable.strings |
| .stringsdict | 处理复数形式(Plural) | apple_count = one/many |
| .xcloc | 导出/导入翻译文件,方便交给翻译团队 | Localizations/en.xcloc |
| .xcstrings | Xcode 14+ 新增,官方推荐的统一多语言资源文件,支持 UI 编辑和团队协作 | Localizable.xcstrings |
| InfoPlist.strings | 专门用于 Info.plist 中的系统提示文案 | 权限提示、App 名称 |
2. 新一代 .xcstrings 文件
从 Xcode 14 开始,Apple 引入了 .xcstrings 文件,来替代过去 .strings 的分散管理问题。
2.1 如何创建
- 在 Xcode 中 新建文件 → 选择 String Catalog
- 命名为 Localizable.xcstrings
- 勾选需要支持的语言
Xcode 会自动生成一个统一的 可视化翻译管理器,再也不用手动管理一堆 .strings 文件。
2.2 使用方式
与 .strings 完全兼容:
// Swift / UIKit
label.text = NSLocalizedString("welcome_message", comment: "欢迎语")
// SwiftUI
Text("welcome_message")
.xcstrings 内部依旧会维护 key-value 翻译表,但你可以在 Xcode 翻译面板 里直接编辑,每种语言对应一列,十分直观。
2.3 优势
- ✅ 翻译集中管理(不用再翻来翻去找 Localizable.strings)
- ✅ 支持协作(团队开发时更不容易冲突)
- ✅ 完全兼容 NSLocalizedString / SwiftUI Text
- ✅ Xcode 内置翻译检测,防止漏翻
3. UIKit 多语言适配
UIKit 中最常用的做法就是 NSLocalizedString:
// Localizable.strings (English)
"welcome_message" = "Welcome, %@!";
// Localizable.strings (Chinese)
"welcome_message" = "欢迎你,%@!";
// Swift
let userName = "Alice"
label.text = String(format: NSLocalizedString("welcome_message", comment: ""), userName)
📌 注意:
- 占位符要用 %@ / %d 等格式化符号
- Info.plist 文案要放在 InfoPlist.strings 中
4. SwiftUI 多语言适配
SwiftUI 的 Text 支持 LocalizedStringKey,所以写起来更简洁:
// Localizable.strings
"hello_world" = "你好,世界!"
struct ContentView: View {
var body: some View {
Text("hello_world") // 自动根据语言切换
}
}
动态切换语言(App 内切换)
SwiftUI 提供了 @Environment(.locale):
struct ContentView: View {
@Environment(\.locale) var locale
var body: some View {
VStack {
Text("hello_world")
Button("切换到英文") {
LocaleManager.shared.current = Locale(identifier: "en")
}
}
}
}
class LocaleManager: ObservableObject {
static let shared = LocaleManager()
@Published var current: Locale = .current
}
然后在 SceneDelegate 或 App 中注入:
@main
struct MyApp: App {
@StateObject private var localeManager = LocaleManager.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.locale, localeManager.current)
}
}
}
这样用户就可以在应用内自由切换语言。
5. UIKit vs SwiftUI 多语言对比
| 功能 | UIKit | SwiftUI |
|---|---|---|
| 基础文案 | NSLocalizedString | Text(“key”) |
| 占位符 | String(format:) | 需要 NSLocalizedString + 拼接 |
| InfoPlist 文案 | InfoPlist.strings | 一样 |
| 动态切换语言 | 自定义 Bundle | @Environment(.locale) |
| 布局适配 | Auto Layout | HStack/VStack 更自然 |
| 文件管理 | .strings / .xcstrings | .strings / .xcstrings |
6. 最佳实践清单(Checklist)
✅ 使用 .xcstrings 集中管理翻译(推荐)
✅ 保持 key 语义化(如 welcome_user,不要写成 text1)
✅ 所有 Info.plist 文案放到 InfoPlist.strings
✅ UI 避免硬编码宽度,保证文案可扩展
✅ 上线前用 伪本地化(Pseudo-Localization) 检查漏翻
✅ 考虑 App 内切换语言,尤其是出海产品
结语
- 如果你是 老项目:继续用 .strings 没问题,但可以逐步迁移到 .xcstrings
- 如果你是 新项目:强烈推荐直接用 .xcstrings,省心、省力、团队协作友好
- SwiftUI 写多语言比 UIKit 简洁,但复杂情况仍需要 NSLocalizedString
1万+

被折叠的 条评论
为什么被折叠?



