Localizing In Xcode
Localizing and Varying Text with a String Catalog
Your app's success hinges on delivering an exceptional experience to users across different locales. Localization is more than just translating text; it involves handling plurals, adapting content for specific devices, and ensuring your app speaks the user's language. In this blog post, we'll explore how to achieve this using string catalogs in Xcode.
What Is a String Catalog?
A string catalog is a powerful tool that allows you to:
- Localize all your app's text.
- Translate strings visually within Xcode.
- Handle plurals for nouns and units.
- Vary text based on specific devices.
Making Text Localizable
Before translation, you need to make your text localizable. Here's how:
-
Wrap User-Facing Strings:
- In SwiftUI, string literals within a view are automatically localizable:
// SwiftUI localizable text Text("Welcome")
- For non SwiftUI, use the
String(localized:)
initializer:// General localizable text String(localized: "Buy a book")
- In SwiftUI, string literals within a view are automatically localizable:
-
Add Context Comments:
-
Assist localizers by providing context:
// Localizable text with comments Text("Explore", comment: "The title of the tab bar item that navigates to the Explore screen.") String(localized: "Get Started", comment: "The label on the Get Started button that appears after sign-in.")
-
Adding a String Catalog to Your Project
-
Create a String Catalog:
- Choose File > New > File in Xcode.
- Select the platform, enter "string" into the filter field, and choose String Catalog.
- Name it (e.g., "Localizable").
- Xcode will automatically track localizable strings from your code.
-
Multiple String Catalogs:
-
If your catalog grows, create multiple string catalog files within the same project.
-
Pass the catalog name to localization APIs:
// SwiftUI pointing to a specific string catalog Text("Explore", tableName: "Navigation") // General text pointing to a specific string catalog String(localized: "Get Started", table: "MainScreen")
-
-
Adding Languages:
- To support multiple languages, add additional languages to your project.
- Xcode keeps your string catalog and app in sync during builds.
Conclusion
String catalogs simplify localization, streamline translations, and enhance the user experience.
References:
- https://developer.apple.com/documentation/xcode/localizing-and-varying-text-with-a-string-catalog
- https://developer.apple.com/documentation/xcode/adding-support-for-languages-and-regions
- https://developer.apple.com/documentation/xcode/localization
Read more
- Safari in SwiftUI • 2 minutes reading time.
- SwiftLeeds 2024, Day 1 • 11 minutes reading time.
- Variadic Parameters • 3 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook