Article source: www.cocoachina.com/industry/20...
Developing a great iOS application is an amazing thing, but there is more to do than good code, gorgeous design, and intuitive interaction. To be in the forefront of the App Store rankings also requires timely product marketing, the ability to expand the user base, practical tools, and the technology to acquire users as widely as possible.
For many developers, the international market is an afterthought, but because the App Store provides a seamless global sharing model, any iOS developer can publish applications to markets in more than 150 countries with one click. Asia and Europe represent a growing market for potential customers. Many people in these two markets are not native English speakers, but in order for the application to take full advantage of the market's potential, you must at least internationalize the application language.
This tutorial will take you to understand the most basic concepts of internationalization through an application called iLikeIt, and add internationalization support to your application. This sample application has a label and a You Like? Button. Whenever the user clicks You Like?, some optimistic sales data and corresponding pictures will fade in from the bottom of the button.
But for now, the app is only available in English.
|Note: Another important aspect of internationalization is to use Auto Layout to change the size of the text. But in order to keep this tutorial as simple as possible, we will not mainly focus on Auto Layout. For the topic of Auto Layout, we have other tutorials .|
Internationalization vs Localization ( Internationalization vs Localization )
Before you start this tutorial, it is important to understand the difference between internationalization and localization. Many people often confuse these two concepts.
Simply put, internationalization is a process of designing applications for international compatibility, such as:
1. Process text input and output in the user's native language;
2. Deal with different date, time and number formats;
3. Use the appropriate calendar and time zone to process the data;
Internationalization is an activity that you and the developer achieve by using the API provided by the system, and make some additions and modifications to the code, so that the Chinese version and the Arabic version of the application are as good as the English version.
In contrast, localization is just translating the user interface and resources of the application into different languages. This is a job you can and should give to others, unless you are proficient in every language that the app should support.
Start now ( Getting Started )
The first step is to download the iLikeIt project, we will use it throughout the tutorial.
Open the project in Xcode 5 and run it on the simulator, you will see the following interface:
As you can see from the screenshot, you need to localize four items:
UI element: Hello Label
UI elements: You like? Button
Sales data text: Yesterday you sold 1000000 apps
Picture text: I LIKE IT
Spend a short time browsing files and folders to familiarize yourself with the project structure. Main.storyboard contains a single screen, which is an instance of the ViewController class.
Separate text from code
Currently, all the text displayed by the application is a hard-coded string in Main.storyboard and ViewController. In order to localize these strings, you need to put them in a separate file.
You will simply quote these strings in the package instead of hard-coding them in your method.
Xcode uses files with a ".strings" extension to store and retrieve all strings used in the app to support each language. According to the language currently used by the iOS device, a simple method call in the code will find and return the required string of characters.
Give it a try, open File>New>File, select Strings Fils in Resource, as shown in the figure:
Click Next, name the file Localizable.strings, and click save.
|Note: Localizable.strings is the default file name used by iOS to localize text. Please refrain from the urge to name it with other content, otherwise you will have to enter the .strings file name again and again every time you quote a localized string.|
Now that you have created the Localizable.strings file, you need to add all the text-the text currently hard-coded in the app. You need to follow a specific but simple format:
"KEY" = "CONTENT"; Copy code
These key/content pairs function like NSDictionary, and the convention is to use the default content translation as the content key: For example, You Like?, you should write:
"You like?" = "You like?"; Copy code
Key/content pairs can also contain format strings:
"Yesterday you sold %@ apps" = "Yesterday you sold %@ apps"; Copy code
Now switch to ViewController.m and find the viewDidLoad method. Now the app will set the text for likeButton and salesCountLabel, as shown below:
_salesCountLabel.text = [NSString stringWithFormat:@"Yesterday you sold %@ apps", @(1000000)]; [_likeButton setTitle:@"You like?" forState:UIControlStateNormal]; Copy code
Instead, you need to read the strings from the Localizable.strings file created earlier. Use a macro named NSLocalizedString to modify these two lines of code as follows:
_salesCountLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Yesterday you sold %@ apps", nil), @(1000000)]; [_likeButton setTitle:NSLocalizedString(@"You like?", nil) forState:UIControlStateNormal]; Copy code
The macro package wraps a slightly longer code fragment into a more manageable length, which is created using the #define directive. If you want to know what the NSLocalizedString macro is, you can hold down the Control key and click on NSLocalizedString, you can see its definition as follows:
#define NSLocalizedString(key, comment) [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil] Copy code
In the current language, the NSLocalizedString macro uses the localizedStringForKey method to find a string with a given key value. It passes nil for the table name, so it uses the default string file name (Localizable.strings). For more details, see Apple's NSBundle Class Reference .
|Note: This macro takes the comment as a parameter, but it seems useless. Instead of manually typing each key/value pair into Localizable.strings as before, you can also use a tool called genstrings that comes with the iOS SDK to automatically process it (very suitable for large projects).|
If you use this method, you can add a comment to each string, and the comment will be displayed beside the default string as an aid to the translator. For example, you can add a comment to indicate where the string is used.
Already have enough background information, let's start now!
Create and run your project, and it should display the same text on the main screen as before, but where is Spanish? Now that your application has been localized, adding translation is a trivial matter.
Add Spanish localization ( Adding A Spanish Localization )
To add support for another language, you can click on the iLikeIt project folder in the left pane, select Project (not Target) in the next pane, and then you will see a Localizations section under the Info tab. Click on the "+", and then select Spanish (es).
The next screen will ask you which files need to be localized. Select all files and click Finish. Note: Localizable.strings is not shown in this list, but don't panic!
At this point, Xcode has already set up some directories behind the scenes. These directories contain different versions of InfoPlist.strings and Main.storyboard for your language of choice. You can use Finder to open the project folder and see, you will see as shown in the figure:
Have you seen en.lproj and es.lproj? They contain specific language versions of files.
en is the localization code for English, and es is the localization code for Spanish. For other languages, you can see the complete list of language codes .
From now on, when your app wants to get the English version of a file, it will look in en.lproj, and when it wants the Spanish version of a file, it will look in es.lproj . very simple! Put your resource files in a suitable folder, and iOS will take care of the rest.
But wait, what about Localizable.strings? To let Xcode know that you want to localize it, you can select the file in the left pane, and then open the File Inspector in the right pane.
You will see a Localize tab, click and select English (because it is currently English), and finally click Localize.
Now the File Inspector panel will show the language the file belongs to. Currently, as you can see, the files are only localized for English. Spanish localization can be added by clicking the box on the left of Spanish.
Go back to the left pane and click the arrow next to Localizable.strings, it will show the child elements. There are now two versions of the document: one in English and one in Spanish.
If you want to modify the Spanish text, you can choose Localizable.strings (Spanish) and replace its content with the following:
"Yesterday you sold %@ apps" = "Ayer le vendi %@ aplicaciones"; "You like?" = "~Es bueno?~"; Copy code
Congratulations! Now your app supports two languages!
In order to test and verify that everything is working properly, you can change the display language to Spanish on the emulator/device by opening the settings app and selecting: General -> International -> Language -> Espanol.
If Xcode debugger is still running, you can click "stop" in Xcode, and then click "Build & Run", you will see:
Locale vs Language
1 million is a pretty good sales data, we can add some formats to it to make it look better!
Open ViewController.m and replace the line of code that sets the text for _salesCountLabel with:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; NSString *numberString = [numberFormatter stringFromNumber:@(1000000)]; _salesCountLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Yesterday you sold %@ apps", nil), numberString]; Copy code
Compile and run the application, then the numbers will be easier to recognize.
This is great for Americans, but in Spain, 1 million is written as "1.000.000" instead of "1,000,000". Run the application in the Spanish environment, you will see a comma to separate the zeros. In iOS, number formatting is based on region/country, not language, so in order to understand how a Spanish person views sales data, you can open Settings.ap and navigate to change the region: General -> International -> Region Format- > Spanish -> Spain
Compile and run the application here, and now you will see the correct number format:
With a little extra upfront work, NSNumberFormatter will automatically format your numbers for the appropriate area. If possible, please refuse to reinvent the wheel, because on iOS, it is usually the way Apple does it in order to pay off.
Internationalizing Storyboards (Internationalizing Storyboards)
Elements in the storyboard, such as labels, buttons, and images, can be set in code or directly in the storyboard. When setting up text programming, you have learned how to support multiple languages, but the "Hello" label at the top of the screen does not have an IBOutlet. You can only set its text in Main.storyboard.
You can add an IBOutlet, connect it to the label in Main.storyboard, and then use NSLocalizedString to set its text properties, just like using likeButton and salesCountLabel, but there is a simpler way to localize storyboard elements without any Additional code.
Open the small triangle on the left side of Main.storyboard, and you will see Main.storyboard (Base) and Main.storyboard (Spanish). Click Main.storyboard (Spanish) to open
Open the editor and you will see the localized text in the storyboard. You already have a Hello tag entry as follows:
/* Class = "IBUILabel"; text = "Hello"; ObjectID = "pUp-yc-27W"; */"pUp-yc-27W.text" = "Hello"; Copy code
Replace the two "Hello" with the Spanish translation of "Hola":
/* Class = "IBUILabel"; text = "Hola"; ObjectID = "pUp-yc-27W"; */"pUp-yc-27W.text" = "Hola"; Copy code
|Note: Never directly change the automatically generated ObjectID, and do not copy and paste the above line of code, because the ObjectID of the label may have been different from the one shown above.|
Since the application uses pictures that contain English text, you need to localize the pictures, because scattered English text will make your Spanish application look unprofessional, and it will also detract from the overall ease of use and application. Market potential.
To localize a picture, you first need to download the Spanish version of the picture (right-click> save as on most browsers):
Open Images.xcassets, drag and drop the previously downloaded picture megusta.png and add it to the picture list on the left to add the picture to the Asset catalog. Asset catalogs cannot be internationalized, so you need to have a way to localize images.
Open Localizable.strings (English) and add the following content:
"imageName" = "ilike"; Copy code
Add the following code to the Localizable.strings (Spanish) file:
"imageName" = "megusta"; Copy code
From now on, you will use the imageName key to retrieve the localized version of the image. Open ViewController.m and add the following code to the viewDidLoad method:
[_imageView setImage:[UIImage imageNamed:NSLocalizedString(@"imageName", nil)]]; Copy code
If necessary, switch the emulator/device to Spanish, compile and run, and then you will see a display of localized images.
Now you have all the tools you need to localize your application for many different languages.
|Note: This only applies when there are different file names for each language. A better way is to localize the resource folder, as described in this article .|
As a final reward, let's localize the name of the application. Info.plist has a special file (InfoPlist.strings) in which you can overwrite other languages with strings. To give the application a different Spanish name, open Supporting Files> InfoPlist.strings (Spanish) and insert the following code:
"CFBundleDisplayName" = "Me Gusta"; Copy code
It changes the name of the application, as shown on Springboard.
Exercise: Internationalizing Audio files (Exercise: Internationalizing Audio files)
At this point, you should be familiar with basic internationalization knowledge. This is a simple exercise. You can test your newly acquired knowledge through two different audio files (one in English and one in Spanish), and play the appropriate file based on the language selected by the user.
The following is a brief description of the necessary steps:
1. Download sample audio files .
2. Copy the first audio file of box-en.wav to the project.
3. Open the audio file inspector, select the localization button, and make sure you select English and Spanish as the supported languages.
4. Rename the second audio file (box-es.wav) to be the same as the first name (box-en.wav), and then copy it to the es.Iproj folder.
5. Make sure you select "Replace File" in the Finder prompt.
Where to go
The Final Project contains all the code you wrote in this tutorial.
Now that you know the basic technology needed to internationalize an iPhone app, add foreign language support to your existing app, or add a foreign language support to it when designing your next app. As you can see, it doesn't take much time, and it will allow your app to reach a wider and more diverse audience, and your non-English users will also thank you!
For the actual translation, you can use Google's free translation service ( www.google.com/translate ), but the result may not be perfect. If you can spend some money, then you can consider third-party service providers listed at the bottom of Apple's Internationalization and Localization page.
If you have any questions or suggestions about internationalization, please join the forum discussion!
The problem is here. When you find that after you change the controls on your storyboard, the strings internationalization file does not change. This is indeed a problem. There is a solution. Merge your new interface with the existing MainStoryboard.strings. 1. start the "Terminal" application. Then cd to the Base.lproj directory of the project folder. For example: cd/Users/UserName/Projects/HelloWorld/HelloWorld/Base.lproj Enter the following command at the prompt: ibtool MainStoryboard.storyboard --generate-strings-file New.strings (You can also use another name (New. strings)) Finally, open your xcode strings file. Okay, now you have the new control value and you can translate it. But my suggestion is to set up internationalization at the end of development. If you find the above method troublesome, you can save the existing translation, then delete the current one, and regenerate one with the method above./