You would like to support your app with different languages. For this, in iOS we have a concept called Localization. In this article, we will learn to implement Localization in our app using Swift.
Prerequisites
- macOS
- XCode
So, let's begin by creating a new project in XCode. Click on iOS->App/Single View App->Next.
- Name your project and select the language as Swift. Select a desired location and click on Create.
- To start with Localization, click on your Project Name -> go to Info Tab -> Under Localizations, click on the '+' button.
Add the Languages, that you would like your App to support. I am going to add French and German to my project.
Once you select the language, a similar kind of popup will appear. Check both the checkboxes (Main.storyboard and LaunchScreen.storyboard) and click on Finish.
Now, in Project Navigator you can see different files under Main.storyboard and LaunchScreen.storyboard. Also, in File Inspector, under Localization section select all the languages that you had added in the Info tab.
Now, we will create a new .Strings file. For that, right-click on your Project -> New File -> search for 'strings' -> Select Strings File -> name the file as Localizable.strings -> Create.
NOTE
Name the file as Localizable.strings only.
Once the Strings file is created, click on the Localizable.strings file and in the File Inspector, click on the Localize button.
On clicking the Localize button, a similar popup will appear. Click on Localize.
Now, go to File Inspector again and under Localization, select all the languages that you had added.
This will create different Strings file for different languages under Localizable.strings file. We will be adding keys and their values to these files.
Now create a UI in Main.storyboard. In my project, I have used a UIPickerView to select a language and based on the language selected, I'm displaying title and data.
After you create your UI, go to Localizable files and create some keys and assign the values to the keys that you will be displaying on your UI.
NOTE
Use the same keys in all the Localizable.strings files.
Refer the below code snippets and add the sentences that you will be displaying on your UI in a key-value type.
//In Localizable(English) file
"title" = "Save Trees";
"info" = "Mother Earth has given us many gifts. One of them is trees. Trees are very important to us. Many of our tribes live inside forests which have trees. Trees provide us timber to make furniture. Wild animals depend on trees for food and shelter. Trees help to prevent soil erosion and floods. They give out Oxygen and make the Earth clean and cool. Many products such as paper, gum, rubber etc are obtained from trees. Trees reduce pollution and increase rain. Birds make their nests on trees. So friends, SAVE TREES by not cutting them and make them happy.";
//In Localizable(French) file
"title" = "Sauver des arbres";
"info" = "Mère Terre nous a fait de nombreux cadeaux. L'un d'eux est les arbres. Les arbres sont très importants pour nous. Beaucoup de nos tribus vivent à l'intérieur de forêts qui ont des arbres. Les arbres nous fournissent du bois pour fabriquer des meubles. Les animaux sauvages dépendent des arbres pour se nourrir et s'abriter. Les arbres aident à prévenir l'érosion des sols et les inondations. Ils donnent de l'oxygène et rendent la Terre propre et fraîche. De nombreux produits tels que le papier, la gomme, le caoutchouc, etc. sont obtenus à partir d'arbres. Les arbres réduisent la pollution et augmentent la pluie. Les oiseaux font leurs nids sur les arbres. Alors les amis, SAUVEZ LES ARBRES en ne les coupant pas et rendez-les heureux.";
//In Localizable(German) file
"title" = "Rette Bäume";
"info" = "Mutter Erde hat uns viele Geschenke gemacht. Einer davon sind Bäume. Bäume sind uns sehr wichtig. Viele unserer Stämme leben in Wäldern mit Bäumen. Bäume liefern uns Holz für die Herstellung von Möbeln. Wilde Tiere sind auf Bäume als Nahrung und Unterschlupf angewiesen. Bäume helfen, Bodenerosion und Überschwemmungen zu verhindern. Sie geben Sauerstoff ab und machen die Erde sauber und kühl. Viele Produkte wie Papier, Gummi, Gummi usw. werden aus Bäumen gewonnen. Bäume reduzieren die Umweltverschmutzung und erhöhen den Regen. Vögel bauen ihre Nester auf Bäumen. Also Freunde, RETTET BÄUME, indem ihr sie nicht schneidet und macht sie glücklich.";
As you can see in all the above code snippets, I have kept the keys as "title" and "info". Its important to keep the keys same in all the files as that will be used to fetch the sentences from the Strings files.
Now go to ViewController.swift file. Here, we will first create an extension of String.
extension String {
func localizeString(string: String) - > String {
let path = Bundle.main.path(forResource: string, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
We have created the above extension to reduce number of lines in the code. The above code will search for the 'lproj' directory which contains the Localizable.strings file as per the language selected.
Next, we will create a function as shown below. Paste the code in ViewController.swift file.
func changeLanguage(lang: String) {
lblTitle.text = "title".localizeString(string: lang)
txtInfo.text = "info".localizeString(string: lang)
}
In the above function, I'm assigning the data fetched from the keys to lblTitle and txtInfo respectively. As per the language selected, the data will be fetched from Localizable.strings file and will be assigned based on the keys.
Finally, we will call this function changeLanguage as per the language selected. As I have used UIPickerView in my project, I'm calling the changeLanguage function as per the selected language in UIPickerView.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if languageList[row] == "French" {
changeLanguage(lang: "fr")
} else if languageList[row] == "German" {
changeLanguage(lang: "de")
} else {
changeLanguage(lang: "en")
}
}
If you are using UIPickerView in your project, make sure you have connected dataSource and delegate for UIPickerView from Main.storyboard.
Below is the entire ViewController.swift file for your reference.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak
var txtInfo: UITextView!@IBOutlet weak
var lblTitle: UILabel!@IBOutlet weak
var langPicker: UIPickerView!
var languageList: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
languageList = ["English", "French", "German"]
//by default
changeLanguage(lang: "en")
}
func numberOfComponents( in pickerView: UIPickerView) - > Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) - > Int {
return languageList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) - > String ? {
return languageList[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if languageList[row] == "French" {
changeLanguage(lang: "fr")
} else if languageList[row] == "German" {
changeLanguage(lang: "de")
} else {
changeLanguage(lang: "en")
}
}
func changeLanguage(lang: String) {
lblTitle.text = "title".localizeString(string: lang)
txtInfo.text = "info".localizeString(string: lang)
}
}
extension String {
func localizeString(string: String) - > String {
let path = Bundle.main.path(forResource: string, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
Now, we are good to run the project. Run the project and change your app into different languages!
.