ios-localization by dpearson2699/swift-ios-skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill ios-localization使用字符串目录、现代字符串类型、FormatStyle 和 RTL 感知布局来本地化 iOS 26+ 应用。本地化错误会导致应用在非英语市场被 App Store 拒绝、UI 翻译错误以及布局损坏。从一开始就确保正确的本地化。
从 Xcode 15 / iOS 17 开始,字符串目录取代了 .strings 和 .stringsdict 文件。它们将所有可本地化字符串、复数规则和设备变体统一到一个基于 JSON 的、带有可视化编辑器的文件中。
字符串目录存在的原因:
.strings 文件需要手动管理键,且容易不同步.stringsdict 需要复杂的 XML 来处理复数形式自动提取的工作原理:
Xcode 在每次构建时扫描以下模式:
// SwiftUI -- 自动提取 (LocalizedStringKey)
Text("Welcome back") // key: "Welcome back"
Label("Settings", systemImage: "gear")
Button("Save") { }
Toggle("Dark Mode", isOn: $dark)
// 编程方式 -- 自动提取
String(localized: "No items found")
LocalizedStringResource("Order placed")
// 不会被提取 -- 普通 String,未本地化
let msg = "Hello" // 只是一个 String,Xcode 无法识别
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
Xcode 会自动将发现的键添加到字符串目录。在编辑器中,可以将翻译标记为“需要审查”、“已翻译”或“已过时”。
有关详细的字符串目录工作流程、迁移和测试策略,请参阅 references/string-catalogs.md。
SwiftUI 视图的文本参数接受 LocalizedStringKey。字符串字面量会被隐式转换——无需额外工作。
// 这些都会自动创建 LocalizedStringKey 查找:
Text("Welcome back")
Label("Profile", systemImage: "person")
Button("Delete") { deleteItem() }
NavigationTitle("Home")
当直接将字符串传递给 SwiftUI 视图初始化器时,使用 LocalizedStringKey。在大多数情况下,不要手动构造 LocalizedStringKey。
用于 SwiftUI 视图初始化器之外的任何本地化字符串。返回一个普通的 String。适用于 iOS 16+。
// 基本用法
let title = String(localized: "Welcome back")
// 带默认值(键与英文文本不同)
let msg = String(localized: "error.network",
defaultValue: "Check your internet connection")
// 带表和包
let label = String(localized: "onboarding.title",
table: "Onboarding",
bundle: .module)
// 带翻译者注释
let btn = String(localized: "Save",
comment: "Button title to save the current document")
当需要将本地化字符串传递给稍后解析的 API(App Intents、小组件、通知、系统框架)时使用。适用于 iOS 16+。
// App Intents 需要 LocalizedStringResource
struct OrderCoffeeIntent: AppIntent {
static var title: LocalizedStringResource = "Order Coffee"
}
// 小组件
struct MyWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "timer",
provider: Provider()) { entry in
TimerView(entry: entry)
}
.configurationDisplayName(LocalizedStringResource("Timer"))
}
}
// 传递但暂不解析
func showAlert(title: LocalizedStringResource, message: LocalizedStringResource) {
// 在显示时根据用户当前区域设置解析
let resolved = String(localized: title)
}
| 上下文 | 类型 | 原因 |
|---|---|---|
| SwiftUI 视图文本参数 | LocalizedStringKey (隐式) | SwiftUI 自动处理查找 |
| 视图模型/服务中的计算字符串 | String(localized:) | 返回用于逻辑的已解析 String |
| App Intents、小组件、系统 API | LocalizedStringResource | 框架在显示时解析 |
| 显示给用户的错误消息 | String(localized:) | 在 catch 块中解析 |
| 日志记录/分析(非面向用户) | 普通 String | 无需本地化 |
本地化字符串中的插值值会成为位置参数,翻译者可以重新排序。
// 英文:"Welcome, Alice! You have 3 new messages."
// 德文:"Willkommen, Alice! Sie haben 3 neue Nachrichten."
// 日文:"Alice さん、新しいメッセージが 3 件あります。"
let text = String(localized: "Welcome, \(name)! You have \(count) new messages.")
在字符串目录中,这会显示为 %@ 和 %lld 占位符,翻译者可以重新排序:
"Welcome, %@! You have %lld new messages.""%@さん、新しいメッセージが%lld件あります。"类型安全的插值(优于格式说明符):
// 插值提供类型安全
String(localized: "Score: \(score, format: .number)")
String(localized: "Due: \(date, format: .dateTime.month().day())")
字符串目录原生处理复数形式——无需 .stringsdict XML。
当本地化字符串包含整数插值时,Xcode 会检测到它,并在字符串目录编辑器中提供复数变体。为每个 CLDR 复数类别提供翻译:
| 类别 | 英文示例 | 阿拉伯文示例 |
|---|---|---|
| zero | (未使用) | 0 items |
| one | 1 item | 1 item |
| two | (未使用) | 2 items (双数) |
| few | (未使用) | 3-10 items |
| many | (未使用) | 11-99 items |
| other | 2+ items | 100+ items |
英文仅使用 one 和 other。阿拉伯文使用全部六个。始终提供 other 作为后备。
// 代码 -- 单个插值触发复数支持
Text("\(unreadCount) unread messages")
// 字符串目录条目(英文):
// one: "%lld unread message"
// other: "%lld unread messages"
字符串目录支持设备特定的文本(iPhone vs iPad vs Mac):
// 在字符串目录编辑器中,为某个键启用 "Vary by Device"
// iPhone: "Tap to continue"
// iPad: "Tap or click to continue"
// Mac: "Click to continue"
使用 ^[...] 屈折变化语法实现自动语法一致性:
// 在支持的语言中自动调整性别/数量
Text("^[\(count) \("photo")](inflect: true) added")
// 英文:"1 photo added" / "3 photos added"
// 西班牙文:"1 foto agregada" / "3 fotos agregadas"
切勿硬编码日期、数字或度量单位格式。使用 FormatStyle (iOS 15+),以便格式化自动适应用户的区域设置。
let now = Date.now
// 预设样式
now.formatted(date: .long, time: .shortened)
// 美国:"January 15, 2026 at 3:30 PM"
// 德国:"15. Januar 2026 um 15:30"
// 日本:"2026年1月15日 15:30"
// 基于组件
now.formatted(.dateTime.month(.wide).day().year())
// 美国:"January 15, 2026"
// 在 SwiftUI 中
Text(now, format: .dateTime.month().day().year())
let count = 1234567
count.formatted() // "1,234,567" (美国) / "1.234.567" (德国)
count.formatted(.number.precision(.fractionLength(2)))
count.formatted(.percent) // 对于 0.85 -> "85%" (美国) / "85 %" (法国)
// 货币
let price = Decimal(29.99)
price.formatted(.currency(code: "USD")) // "$29.99" (美国) / "29,99 $US" (法国)
price.formatted(.currency(code: "EUR")) // "29,99 EUR" (德国)
let distance = Measurement(value: 5, unit: UnitLength.kilometers)
distance.formatted(.measurement(width: .wide))
// 美国:"3.1 miles" (自动转换!) / 德国:"5 Kilometer"
let temp = Measurement(value: 22, unit: UnitTemperature.celsius)
temp.formatted(.measurement(width: .abbreviated))
// 美国:"72 F" (自动转换!) / 法国:"22 C"
// 时长
let dur = Duration.seconds(3661)
dur.formatted(.time(pattern: .hourMinuteSecond)) // "1:01:01"
// 人名
let name = PersonNameComponents(givenName: "John", familyName: "Doe")
name.formatted(.name(style: .long)) // "John Doe" (美国) / "Doe John" (日本)
// 列表
let items = ["Apples", "Oranges", "Bananas"]
items.formatted(.list(type: .and)) // "Apples, Oranges, and Bananas" (英文)
// "Apples, Oranges et Bananas" (法文)
有关完整的 FormatStyle 参考、自定义样式和 RTL 布局,请参阅 references/formatstyle-locale.md。
SwiftUI 会自动为 RTL 语言(阿拉伯语、希伯来语、乌尔都语、波斯语)镜像布局。大多数视图无需任何更改。
HStack 子元素顺序反转.leading / .trailing 对齐方式和内边距交换位置NavigationStack 返回按钮移动到 trailing 边缘List 展开指示符翻转// 在预览中测试 RTL
MyView()
.environment(\.layoutDirection, .rightToLeft)
.environment(\.locale, Locale(identifier: "ar"))
// 应该镜像的图像(方向箭头、进度指示器)
Image(systemName: "chevron.right")
.flipsForRightToLeftLayoutDirection(true)
// 不应该镜像的图像:徽标、照片、时钟、音符
// 特定内容强制 LTR(电话号码、代码)
Text("+1 (555) 123-4567")
.environment(\.layoutDirection, .leftToRight)
.leading / .trailing —— 它们会自动为 RTL 翻转.left / .right —— 它们是固定的,会破坏 RTLHStack / VStack —— 它们遵循布局方向offset(x:) 进行方向定位// 错误 -- 遗留 API,冗长,没有与字符串目录的编译器集成
let title = NSLocalizedString("welcome_title", comment: "Welcome screen title")
// 正确
let title = String(localized: "welcome_title",
defaultValue: "Welcome!",
comment: "Welcome screen title")
// 或者在 SwiftUI 中,直接:
Text("Welcome!")
// 错误 -- 词序因语言而异
let greeting = String(localized: "Hello") + ", " + name + "!"
// 正确 -- 翻译者可以重新排序占位符
let greeting = String(localized: "Hello, \(name)!")
// 错误 -- 仅限美国格式
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy" // 在大多数国家没有意义
// 正确 -- 适应用户区域设置
Text(date, format: .dateTime.month().day().year())
// 错误 -- 德文文本比英文长约 30%
Text(title).frame(width: 120)
// 正确
Text(title).fixedSize(horizontal: false, vertical: true)
// 或者使用能适应扩展的 VStack/换行
// 错误 -- 不会为 RTL 翻转
HStack { Spacer(); text }.padding(.left, 16)
// 正确
HStack { Spacer(); text }.padding(.leading, 16)
// 错误 -- 未本地化
let errorMessage = "Something went wrong"
showAlert(message: errorMessage)
// 正确
let errorMessage = LocalizedStringResource("Something went wrong")
showAlert(message: String(localized: errorMessage))
仅用英文测试会隐藏截断、布局和 RTL 错误。
使用 Xcode 方案设置来覆盖应用语言,而无需更改设备区域设置。
LocalizedStringKey 或 String(localized:))FormatStyle,而非硬编码格式.leading / .trailing,而非 .left / .right.flipsForRightToLeftLayoutDirection(true)LocalizedStringResourceNSLocalizedString@ScaledMetric,以便随动态类型缩放references/formatstyle-locale.mdreferences/string-catalogs.md每周安装量
397
代码仓库
GitHub 星标数
269
首次出现
2026年3月3日
安全审计
安装于
codex394
kimi-cli391
amp391
cline391
github-copilot391
opencode391
Localize iOS 26+ apps using String Catalogs, modern string types, FormatStyle, and RTL-aware layout. Localization mistakes cause App Store rejections in non-English markets, mistranslated UI, and broken layouts. Ship with correct localization from the start.
String Catalogs replaced .strings and .stringsdict files starting in Xcode 15 / iOS 17. They unify all localizable strings, pluralization rules, and device variations into a single JSON-based file with a visual editor.
Why String Catalogs exist:
.strings files required manual key management and fell out of sync.stringsdict required complex XML for pluralsHow automatic extraction works:
Xcode scans for these patterns on each build:
// SwiftUI -- automatically extracted (LocalizedStringKey)
Text("Welcome back") // key: "Welcome back"
Label("Settings", systemImage: "gear")
Button("Save") { }
Toggle("Dark Mode", isOn: $dark)
// Programmatic -- automatically extracted
String(localized: "No items found")
LocalizedStringResource("Order placed")
// NOT extracted -- plain String, not localized
let msg = "Hello" // just a String, invisible to Xcode
Xcode adds discovered keys to the String Catalog automatically. Mark translations as Needs Review, Translated, or Stale in the editor.
For detailed String Catalog workflows, migration, and testing strategies, see references/string-catalogs.md.
SwiftUI views accept LocalizedStringKey for their text parameters. String literals are implicitly converted -- no extra work needed.
// These all create a LocalizedStringKey lookup automatically:
Text("Welcome back")
Label("Profile", systemImage: "person")
Button("Delete") { deleteItem() }
NavigationTitle("Home")
Use LocalizedStringKey when passing strings directly to SwiftUI view initializers. Do not construct LocalizedStringKey manually in most cases.
Use for any localized string outside a SwiftUI view initializer. Returns a plain String. Available iOS 16+.
// Basic
let title = String(localized: "Welcome back")
// With default value (key differs from English text)
let msg = String(localized: "error.network",
defaultValue: "Check your internet connection")
// With table and bundle
let label = String(localized: "onboarding.title",
table: "Onboarding",
bundle: .module)
// With comment for translators
let btn = String(localized: "Save",
comment: "Button title to save the current document")
Use when you need to pass a localized string to an API that resolves it later (App Intents, widgets, notifications, system frameworks). Available iOS 16+.
// App Intents require LocalizedStringResource
struct OrderCoffeeIntent: AppIntent {
static var title: LocalizedStringResource = "Order Coffee"
}
// Widgets
struct MyWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: "timer",
provider: Provider()) { entry in
TimerView(entry: entry)
}
.configurationDisplayName(LocalizedStringResource("Timer"))
}
}
// Pass around without resolving yet
func showAlert(title: LocalizedStringResource, message: LocalizedStringResource) {
// Resolved at display time with the user's current locale
let resolved = String(localized: title)
}
| Context | Type | Why |
|---|---|---|
| SwiftUI view text parameters | LocalizedStringKey (implicit) | SwiftUI handles lookup automatically |
| Computed strings in view models / services | String(localized:) | Returns resolved String for logic |
| App Intents, widgets, system APIs | LocalizedStringResource | Framework resolves at display time |
| Error messages shown to users | String(localized:) | Resolved in catch blocks |
Interpolated values in localized strings become positional arguments that translators can reorder.
// English: "Welcome, Alice! You have 3 new messages."
// German: "Willkommen, Alice! Sie haben 3 neue Nachrichten."
// Japanese: "Alice さん、新しいメッセージが 3 件あります。"
let text = String(localized: "Welcome, \(name)! You have \(count) new messages.")
In the String Catalog, this appears with %@ and %lld placeholders that translators can reorder:
"Welcome, %@! You have %lld new messages.""%@さん、新しいメッセージが%lld件あります。"Type-safe interpolation (preferred over format specifiers):
// Interpolation provides type safety
String(localized: "Score: \(score, format: .number)")
String(localized: "Due: \(date, format: .dateTime.month().day())")
String Catalogs handle pluralization natively -- no .stringsdict XML required.
When a localized string contains an integer interpolation, Xcode detects it and offers plural variants in the String Catalog editor. Supply translations for each CLDR plural category:
| Category | English example | Arabic example |
|---|---|---|
| zero | (not used) | 0 items |
| one | 1 item | 1 item |
| two | (not used) | 2 items (dual) |
| few | (not used) | 3-10 items |
| many | (not used) | 11-99 items |
| other | 2+ items | 100+ items |
English uses only one and other. Arabic uses all six. Always supply other as the fallback.
// Code -- single interpolation triggers plural support
Text("\(unreadCount) unread messages")
// String Catalog entries (English):
// one: "%lld unread message"
// other: "%lld unread messages"
String Catalogs support device-specific text (iPhone vs iPad vs Mac):
// In String Catalog editor, enable "Vary by Device" for a key
// iPhone: "Tap to continue"
// iPad: "Tap or click to continue"
// Mac: "Click to continue"
Use ^[...] inflection syntax for automatic grammatical agreement:
// Automatically adjusts for gender/number in supported languages
Text("^[\(count) \("photo")](inflect: true) added")
// English: "1 photo added" / "3 photos added"
// Spanish: "1 foto agregada" / "3 fotos agregadas"
Never hard-code date, number, or measurement formats. Use FormatStyle (iOS 15+) so formatting adapts to the user's locale automatically.
let now = Date.now
// Preset styles
now.formatted(date: .long, time: .shortened)
// US: "January 15, 2026 at 3:30 PM"
// DE: "15. Januar 2026 um 15:30"
// JP: "2026年1月15日 15:30"
// Component-based
now.formatted(.dateTime.month(.wide).day().year())
// US: "January 15, 2026"
// In SwiftUI
Text(now, format: .dateTime.month().day().year())
let count = 1234567
count.formatted() // "1,234,567" (US) / "1.234.567" (DE)
count.formatted(.number.precision(.fractionLength(2)))
count.formatted(.percent) // For 0.85 -> "85%" (US) / "85 %" (FR)
// Currency
let price = Decimal(29.99)
price.formatted(.currency(code: "USD")) // "$29.99" (US) / "29,99 $US" (FR)
price.formatted(.currency(code: "EUR")) // "29,99 EUR" (DE)
let distance = Measurement(value: 5, unit: UnitLength.kilometers)
distance.formatted(.measurement(width: .wide))
// US: "3.1 miles" (auto-converts!) / DE: "5 Kilometer"
let temp = Measurement(value: 22, unit: UnitTemperature.celsius)
temp.formatted(.measurement(width: .abbreviated))
// US: "72 F" (auto-converts!) / FR: "22 C"
// Duration
let dur = Duration.seconds(3661)
dur.formatted(.time(pattern: .hourMinuteSecond)) // "1:01:01"
// Person names
let name = PersonNameComponents(givenName: "John", familyName: "Doe")
name.formatted(.name(style: .long)) // "John Doe" (US) / "Doe John" (JP)
// Lists
let items = ["Apples", "Oranges", "Bananas"]
items.formatted(.list(type: .and)) // "Apples, Oranges, and Bananas" (EN)
// "Apples, Oranges et Bananas" (FR)
For the complete FormatStyle reference, custom styles, and RTL layout, see references/formatstyle-locale.md.
SwiftUI automatically mirrors layouts for RTL languages (Arabic, Hebrew, Urdu, Persian). Most views require zero changes.
HStack children reverse order.leading / .trailing alignment and padding swap sidesNavigationStack back button moves to trailing edgeList disclosure indicators flip// Testing RTL in previews
MyView()
.environment(\.layoutDirection, .rightToLeft)
.environment(\.locale, Locale(identifier: "ar"))
// Images that should mirror (directional arrows, progress indicators)
Image(systemName: "chevron.right")
.flipsForRightToLeftLayoutDirection(true)
// Images that should NOT mirror: logos, photos, clocks, music notes
// Forced LTR for specific content (phone numbers, code)
Text("+1 (555) 123-4567")
.environment(\.layoutDirection, .leftToRight)
.leading / .trailing -- they auto-flip for RTL.left / .right -- they are fixed and break RTLHStack / VStack -- they respect layout directionoffset(x:) for directional positioning// WRONG -- legacy API, verbose, no compiler integration with String Catalogs
let title = NSLocalizedString("welcome_title", comment: "Welcome screen title")
// CORRECT
let title = String(localized: "welcome_title",
defaultValue: "Welcome!",
comment: "Welcome screen title")
// Or in SwiftUI, just:
Text("Welcome!")
// WRONG -- word order varies by language
let greeting = String(localized: "Hello") + ", " + name + "!"
// CORRECT -- translators can reorder placeholders
let greeting = String(localized: "Hello, \(name)!")
// WRONG -- US-only format
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy" // Meaningless in most countries
// CORRECT -- adapts to user locale
Text(date, format: .dateTime.month().day().year())
// WRONG -- German text is ~30% longer than English
Text(title).frame(width: 120)
// CORRECT
Text(title).fixedSize(horizontal: false, vertical: true)
// Or use VStack/wrapping that accommodates expansion
// WRONG -- does not flip for RTL
HStack { Spacer(); text }.padding(.left, 16)
// CORRECT
HStack { Spacer(); text }.padding(.leading, 16)
// WRONG -- not localized
let errorMessage = "Something went wrong"
showAlert(message: errorMessage)
// CORRECT
let errorMessage = LocalizedStringResource("Something went wrong")
showAlert(message: String(localized: errorMessage))
Testing only in English hides truncation, layout, and RTL bugs.
Use Xcode scheme settings to override the app language without changing device locale.
LocalizedStringKey in SwiftUI or String(localized:))FormatStyle, not hardcoded formats.leading / .trailing, not .left / .right.flipsForRightToLeftLayoutDirection(true)LocalizedStringResourcereferences/formatstyle-locale.mdreferences/string-catalogs.mdWeekly Installs
397
Repository
GitHub Stars
269
First Seen
Mar 3, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex394
kimi-cli391
amp391
cline391
github-copilot391
opencode391
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
| Logging / analytics (not user-facing) |
Plain String |
| No localization needed |
NSLocalizedString usage in new code@ScaledMetric used for spacing that must scale with Dynamic Type