Implementing Localization
1. Using NSLocalizedString
| Property | Value | Description |
|---|---|---|
| NSLocalizedString(key: String) | NSLocalizedString("greeting", comment: "A friendly greeting") |
Looks up a localized string in the main bundle using the specified key. |
| NSLocalizedString(key: String, comment: String) | NSLocalizedString("welcome_message", comment: "Welcome message for user") |
Looks up a localized string in the main bundle using the specified key and includes a comment for translators. |
| NSLocalizedString(key: String, tableName: String) | NSLocalizedString("error_code", tableName: "Errors") |
Looks up a localized string in the specified table (e.g., Errors.strings). |
Example: Basic Usage of NSLocalizedString
let greeting = NSLocalizedString("greeting", comment: "A friendly greeting")
print(greeting)
Example: Using NSLocalizedString with Table
let errorMessage = NSLocalizedString("network_error", tableName: "Errors", comment: "Error when network is down")
print(errorMessage)
Note: The
comment field is used by localization tools to provide context to translators. It does not affect runtime behavior.
Warning: If a localized string is not found for the key,
NSLocalizedString returns the key itself as a fallback. Ensure all keys are present in localization files.
2. Creating Localizable.strings Files
| File Name | Content Format | Description |
|---|---|---|
| Localizable.strings | "key" = "value"; |
Main file for string localization in iOS apps |
| Localizable.stringsdict | <key>key</key><dict>...</dict> |
Used for pluralization and gender-specific strings |
Example: Basic Localizable.strings
"welcome_message" = "Welcome to our app!";
"greeting_name" = "Hello, %@";
"button_save" = "Save";
Example: Localizable.stringsdict for Plurals
<dict>
<key>item_count</key>
<dict>
<key>NSStringLocalizedStorage</key>
<string>item_count</string>
<key>NSStringFormatSpecifiers</key>
<array>
<string>%d</string>
</array>
<key>one</key>
<string>You have %d item.</string>
<key>other</key>
<string>You have %d items.</string>
</dict>
</dict>
Note: The
Localizable.strings file must be placed in the appropriate language folder within your app's bundle (e.g., en.lproj/Localizable.strings for English).Warning: Avoid using special characters like
<, >, or & in your strings without proper escaping. Use \ for escaping.3. Localizing Storyboards and XIBs
Storyboard and XIB files can be localized using the built-in localization features in Xcode. This involves creating localized versions of these files for each supported language.
| Step | Description | Action |
|---|---|---|
| 1 | Create a new localization for the storyboard or XIB file | Right-click on the file in Xcode → Localize... |
| 2 | Select the language to localize | Choose from the list of supported languages in Xcode |
| 3 | Edit localized strings | Modify the text content in the localized file to match the target language |
Example: Localizing a Label in Storyboard
let localizedString = NSLocalizedString("welcome_message", comment: "Welcome message for user")
label.text = localizedString
Note: Ensure that all UI elements in the storyboard or XIB are properly localized to maintain consistency across languages.
4. Supporting Multiple Languages
| Language Code | Full Name | Native Name | Locale Identifier |
|---|---|---|---|
| en | English | English | en |
| es | Spanish | Español | es |
| fr | French | Français | fr |
| de | German | Deutsch | de |
| ja | Japanese | 日本語 | ja |
| ko | Korean | 한국어 | ko |
| zh-Hans | Chinese (Simplified) | 中文(简体) | zh-Hans |
| zh-Hant | Chinese (Traditional) | 中文(繁體) | zh-Hant |
Example: Setting Up Localization in Swift
import Foundation
// Define supported locales
let supportedLocales = [
"en", "es", "fr", "de", "ja", "ko", "zh-Hans", "zh-Hant"
]
// Get current locale
let currentLocale = Locale.current
// Check if the current language is supported
if supportedLocales.contains(currentLocale.languageCode ?? "") {
print("Current locale is supported: \(currentLocale)")
} else {
print("Current locale not supported")
}
Note: Ensure that your app's
Info.plist includes the supported localizations under the CFBundleLocalizations key.
Localization Setup Steps
- Create a
Localizable.stringsfile for each language. - Add localized strings to each
Localizable.stringsfile. - Set the
CFBundleLocalizationskey inInfo.plist. - Use
NSLocalizedStringto retrieve localized strings in code.
5. Using String Formatting for Localization
| Format | Description | Example |
|---|---|---|
| %d | Integer value | String(format: "You have %d messages", 5) |
| %.2f | Float with 2 decimal places | String(format: "Price: $%.2f", 19.99) |
| %s | String value | String(format: "Hello %s", "John") |
| %@ | Object (used in NSFormatting) | String(format: "Welcome %@!", user.name) |
Example: Formatting with Localization
let message = String(format: NSLocalizedString("messages.count", comment: "Number of messages"), 10)
let price = String(format: NSLocalizedString("price.format", comment: "Price formatting"), 29.99)
Note: Always use
NSLocalizedString for localization keys to ensure proper translation handling.
Warning: Avoid hardcoding strings in format specifiers. Use localization keys for dynamic content.
| Localization Key | English Value | French Value | Usage |
|---|---|---|---|
| messages.count | %d messages |
%d messages |
String(format: NSLocalizedString("messages.count", comment: ""), 5) |
| price.format | Price: $%.2f |
Prix: %.2f € |
String(format: NSLocalizedString("price.format", comment: ""), 19.99) |
6. Localizing Images and Assets
| Asset Type | Localization Method | Notes |
|---|---|---|
| Image Assets | UIImage(named: "image_name") |
Use asset catalogs with localized variants. Name files as image_name~iphone.png, image_name~ipad.png |
| Localized Images | UIImage(named: "localized_image", in: bundle, compatibleWith: traitCollection) |
Supports device family and scale variants |
| Asset Catalogs | Use xcassets with localization support |
Allows for image variations per language, region, and device |
Example: Using Asset Catalogs for Localization
let localizedImage = UIImage(named: "logo", in: Bundle.main, compatibleWith: UITraitCollection.current)
Note: Image names should match the base localization key, e.g.,
logo.png for English and logo~zh.png for Chinese.Warning: Ensure all localized image assets are included in the app bundle and properly named to avoid runtime errors.
7. Using Locale for Region-Specific Formatting
| Property | Description | Example |
|---|---|---|
| Locale.identifier | Unique identifier for the locale, e.g., "en_US", "fr_FR" | Locale(identifier: "en_US").identifier |
| Locale.languageCode | Language code, e.g., "en", "fr" | Locale(identifier: "fr_CA").languageCode |
| Locale.country | Country code, e.g., "US", "CA" | Locale(identifier: "fr_CA").region |
Example: Formatting Numbers with Locale
let number = 1234567.89
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "de_DE")
print(formatter.string(for: number)!) // 1.234.567,89
Example: Formatting Dates with Locale
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
formatter.locale = Locale(identifier: "ja_JP")
print(formatter.string(from: date)) // 2026年4月5日 14:30
Note: Use
Locale.current to get the user's preferred locale.
Warning: Ensure that all localized strings are properly loaded using
NSLocalizedString to avoid runtime errors.
8. Testing Different Locales
Example: Simulating Locale in Simulator
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = NSLocalizedString("welcome_title", comment: "Welcome title")
}
}
| Locale | Language Code | Region Code | Notes |
|---|---|---|---|
| en_US | en |
US |
English (United States) |
| es_ES | es |
ES |
Spanish (Spain) |
| fr_FR | fr |
FR |
French (France) |
| de_DE | de |
DE |
German (Germany) |
| ja_JP | ja |
JP |
Japanese (Japan) |
Workflow: Testing Locales in Xcode Simulator
- Open your app in Xcode
- Select the simulator device
- Navigate to
Settings > General > Language & Region - Select desired language from list
- Restart the app to see localized content
Note: Ensure all strings are properly localized in
Localizable.strings files for each supported language.
Warning: Avoid hardcoding strings in code; always use
NSLocalizedString for localization.
9. Using Base Internationalization
Base Internationalization is a powerful feature in iOS that allows developers to create apps with localized content while maintaining a single source of truth for the UI structure. It enables you to define your app's interface in a base localization and then provide localized versions for different languages.
| Property | Description | Notes |
|---|---|---|
| Base.lproj | Directory containing the base localization files | Contains the default UI and strings used when no localized version exists |
| Localizable.strings | File containing translatable strings | Used to store all user-facing text in the app |
| Main.storyboard/.xib | Interface files with localized content | Supports localization through the localizable attribute |
Example: Setting up Base Internationalization
// Create a new localization directory
// In Xcode: Product > Add Localization...
// Select "Base" as the language to create the base localization
// Example of a Localizable.strings file in Base.lproj
"welcome_message" = "Welcome to our app!";
// In a view controller, use the localized string
let welcomeText = NSLocalizedString("welcome_message", comment: "Welcome message for users")
Note: When using Base Internationalization, always ensure that your base localization is kept up-to-date with the latest UI changes to avoid inconsistencies in localized versions.
Warning: Avoid hardcoding strings in your code. Always use
NSLocalizedString or String(localized:) to fetch localized strings.
Key Benefits of Base Internationalization
- Reduces maintenance overhead by centralizing UI structure
- Enables faster localization for new languages
- Improves consistency across localized versions of the app
10. Implementing Right-to-Left Support
| Property | Value | Description |
|---|---|---|
| UIView.semanticContentAttribute | .rightToLeft |
Defines the semantic content direction for a view. |
| UIView.directionalLayoutMargins | NSDirectionalEdgeInsets |
Insets for layout margins in a directional context. |
| UILabel.textAlignment | .right |
Aligns text to the right for RTL layouts. |
Example: Setting Up Right-to-Left Layout
let view = UIView()
view.semanticContentAttribute = .rightToLeft
Example: Using Directional Layout Margins
let margins = NSDirectionalEdgeInsets(
top: 10,
leading: 20,
bottom: 10,
trailing: 20
)
view.directionalLayoutMargins = margins
Note: Ensure that all UI elements are properly mirrored for RTL layouts to maintain usability and visual consistency.
Warning: Not setting
semanticContentAttribute can lead to incorrect layout behavior in RTL environments.