Friday 31 May 2019

String Localization in Xcode

Check example code
https://github.com/Sylvia-YiyinShen/LocalisationExample

Prep work

In Project Info Panel add a language.



Storyboad localization

XCode will prompt to ask you to choose the files/storyboard for localization.
Tap finish, now you should be able to see XCode has generated storyboard.strings for you as below


At the moment it is empty, let's add  label in Main.storyboard
And in File Inspector, un-select the language then select again

Now you should see XCode updated the Main.strings file as


Change the labels to another language.
Edit the scheme by 


Build and re-run, you should see the translated labels.


XCode provides another way to preview the storyboard
You can change the .strings file to a Interface Build Storyboard


Click the converted .storyboard



XIB Localization

However, you will find other XIB outside of any storyboard has not been localized yet, even those existed before you turn on localization. XCode didn't automatically prepare localization for you and even didn't ask you to choose.

Just select XIB, go to File Inspector, and select the language under Localization section.  Similarly, you can choose to convert it to .string or .xib file.



Localize Strings Generated in Code

If you decided to utilize localization at the very beginning, you could create a string file via File -> New -> File

Specify the text in .strings file


Use the localized string


tableName should be the .strings file name



Prepare you strings for Localization

If you don't want localization for now but want to make your strings ready for future requirements.



One day, you want to turn on Localization, select the project, XCode -> Editor -> Export For Localization, XCode will generate a Localizable.strings file contains those strings created via NSLocalizedString(key, comment) along with any other storyboards or XIBs that have been selected localization. Update those exported files, you can choose XCode ->Edit -> Import or just drag the Localizable.strings file into your project.

Drag the file here and link it into XCode, choose the language from Edit Scherme, build and rerun, you should be able to see the transalted texts.





No comments:

Post a Comment