SwiftUI with Localization from the start
strings vs. stringsDict, 3 steps from initial setup to easy testing during Xcode 12.3 SwiftUI development.
It is best to build app with Internationalization in mind and support localization from the start of the project. Get these first 3 steps working first, before worrying about stringsDict, Xcode Localization Catalog, XLIFF, etc.
Step 1: Add Localizations to your project info page
- Make sure “Use Base Internationalization” is checked.
- Add 1 additional locale in addition to your development language, e.g. Chinese, Traditional (zh-Hant)
Step 2: Add Localizable.strings to your project
Don’t worry about stringsDict yet. stringsDict are for more advanced localization problems such as plurals.
Create a “Localizable.strings” file, if you have not done so yet: by clicking File > New > File > Strings File (part of the Resources category). Name it “Localizable.strings”.
Activate “Localization” in the inspector view of the Localizable.strings file to select and confirm the locale strings files you want to create — one file for each locale.
Select a newly created Localizable.strings locale file, e.g. the “Chinese, Traditional” file and add a row to the end: “Hello” = “你好”;
Step 3: Add locale into environment variable for ContentView()
— to make localization testing easier. ContentView() is located in your main app file. For example:
ContentView().environment(\.locale, .init(identifier: “zh-Hant”))
if your project has other environment variables, these can be stacked like this:
.environment(\.locale, .init(identifier: “zh-Hant”))
This means you can test the app by changing the locale parameter.
Step 3 has been summarized from Benoit Pasquier’s page. See first reference below.
After following these 3 steps, Text(“Hello”) in ContentView.swift will show the Chinese version, 你好, when locale is set to zh-Hant. Change the locale back to “en” to switch back to English.
Note 1: LocalizedStringKey is case-sensitive. If the key used in in the strings file is “hello” = “你好”; translation will not occur for Text(“Hello”).
Note 2: When translation fails due to missing key in locale string file, the original key text is displayed without error message, e.g. “Hello”.
Localization with SwiftUI, how to preview your localized content
With SwiftUI being recently introduced, I was curious if we could take advantage of SwiftUI preview to speed up testing…
Internationalizing Your iOS App: Getting Started
In this tutorial, learn how to prepare your app to support multiple languages, including regional numeric formats…
How to: Localize Your SwiftUI Project on Xcode 12
The easiest way to add multi-languages support for your app…
Localized Pluralization with Stringsdict
It's harder to create user-facing strings that contain numbers than it should be. This post should make it easier, with…