1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình iPhone part 17

18 278 1
Tài liệu được quét OCR, nội dung có thể không chính xác
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Chapter 17: Application localization
Thể loại Chapter
Định dạng
Số trang 18
Dung lượng 1,15 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Localization Architecture When a nonlocalized application is run, all of the application’s text will be presented in the developer’s own language, also known as the development base lan

Trang 1

Application

Localization

t the time of this writing, the iPhone is, or will soon be, available in 70 differ- ent countries, and that number will obviously increase over time You can now buy and use an iPhone on every continent except Antarctica If you plan on releasing applications through the iPhone App Store, your potential market is considerably larger than just people in your own country who speak your own language Fortunately, iPhone has a robust localization architecture that lets you easily translate your application (or have it translated by others) into not only multiple languages but even into multiple dialects of the same language Want to provide different terminology to English speakers in the United King- dom than you do to English speakers in the United States? No problem

That is, no problem at all, if you've written your code correctly Retrofitting an exist- ing application to support localization is much harder than writing your application that way from the start In this chapter, we'll show you how to write your code so it

is easy to localize, and then we'll go about localizing a sample application

Localization Architecture

When a nonlocalized application is run, all of the application’s text will be

presented in the developer’s own language, also known as the development base language

When developers decide to localize their application, they create a subdirectory in their application bundle for each supported language Each language's subdirec- tory contains a subset of the application’s resources that were translated into that language Each subdirectory is called a localization project, also called a localiza- tion folder Localization folder names always end with the extension /proj

Trang 2

In the Settings application, the user has the ability to set the language and region format For example, if the user’s language is English, available regions might be United States, Australia, or Hong Kong—all regions in which English is spoken

When a localized application needs to load a resource, such as an image, property list, or nib, the application checks the user’s language and region and looks for a localization folder that matches that setting If it finds one, it will load the localized version of the resource instead

of the base version

For users who selected French as their iPhones’ language and France as their region, the application will look first for a localization folder named fr_FR./proj The first two letters of the folder name are the ISO two-digit code that represents the French language The two letters following the underscore are the ISO country code that represents France

If the application cannot find a match using the two-digit code, it will look for a match using the ISO three-digit code All languages have three-digit codes Only some have two-digit codes

OTE

You can find a list of the current ISO country codes on the ISO web site Both the two- and three-digit codes are part of the ISO 3166 standard: http: //www iso org/iso/country_codes.htm

In our previous example, if the application was unable to find the folder named fr_FR./proj,

it will look for a localization folder named fre_FR or fra_FR All languages have at least one three-digit code; some have two three-digit codes, one for the English spelling of the lan- guage and one for the native spelling When a language has both a two-digit code and

a three-digit code, use the two-digit code

If the application cannot find a folder that is an exact match, it will then look for a localization folder in the application bundle that matches just the language code without the region code

So, staying with our French-speaking person from France, the application would next look for

a localization project called fr./proj If it didn’t find a language project with that name, it would try looking for fre./proj, then fra.[proj If none of those were found, it would look for French.Iproj The last construct exists to support legacy Mac OS X applications, and generally speaking, you should avoid it (though there is an exception to that rule that we'll look at later in this chapter)

If the application doesn’t find a language project that matches either the language/region combination or just the language, it will use the resources from the development base lan- guage If it does find an appropriate localization project, it will always look there first for any resources that it needs If you load a UI Image using imageNamed:, for example, it will look first for an image with the specified name in the localization project If it finds one, it will use

it If it doesn’t, it will fall back to the base language resource

Trang 3

lfan application has more than one localization project that matches, for example, a project called fr_FR.Iproj and one called fr/proj, it will look first in the more specific match, in this case fr_FR.Iproj lf it doesn’t find the resource there, it will look in the fr./proj This gives you the ability

to provide resources common to all speakers of a language in one language project, localizing only those resources that are impacted by differences in dialect or geographic region

You only have to localize resources that are affected by language or country If an image in your application has no words and its meaning is universal, there’s no need to localize that image

Using String Files

What do we do about string literals and string constants in your source code? Consider this source code from the previous chapter:

UIAlertView *alert = [[UIAlertView alloc]

initWithTitle:@"Error accessing photo library"

message:@"Device does not support a photo library”

delegate:nil cancelButtonTitle:@"Drat!"

otherButtonTitles:nil];

[alert show];

[alert release];

If we've gone through the effort of localizing our application for a particular audience, we certainly don’t want to be presenting alerts written in the development base language The answer is to store these strings in special text files call string files String files are noth- ing more than Unicode (UTF-16) text files that contain a list of string pairs, each identified by

a comment

Here is an example of what a strings file might look like in your application

/* Used to ask the user his/her first name */

"First Name" = "First Name";

/* Used to get the user’s last name */

"Last Name” = "Last Name";

/* Used to ask the user’s birth date */

"Birthday" = "Birthday";

The values between the /* and the */ characters are just comments for the translator They are not used in the application and can safely be excluded, though they're a good idea They give context, showing how a particular string is being used in the application.

Trang 4

You'll notice that each line lists the same string twice The string on the left side of the equals sign acts as a key, and it will always contain the same value regardless of language The value

on the right side of the equals sign is the one that gets translated to the local language So, the preceding strings file, localized into French, might look like this:

/* Used to ask the user his/her first name */

"First Name " = "Prénom";

/* Used to get the user’s last name */

"Last Name " = "Nom de famille";

/* Used to ask the user’s birth date */

"Birthday" = “Anniversaire”;

Creating the Strings File

You won't actually create the strings file by hand Instead, you'll embed all localizable text strings in a special macro in your code Once your source code is final and ready for localiza- tion, you'll run a command-line program, named genstrings, which will search all your code files for occurrences of the macro, pulling out all the strings and embedding them in

a localizable strings file

Here’s how the macro works Let's start with a traditional string declaration:

NSString *myString = @"First Name";

To make this string localizable, you'll do this instead:

NSString *myString = NSLocalizedString(@"First Name",

@"Used to ask the user his/her first name");

The NSLocalizedString macro takes two parameters The first is the string value in the base language If there is no localization, the application will use this string The second parameter will be used as a comment in the strings file

NSLocalizedString looks in the application bundle, inside the appropriate localization project, for a strings file named /ocalizable.strings If it does not find the file, it returns its first parameter, and the string will appear in the development base language Strings are typi- cally displayed only in the base language during development, since the application will not yet be localized

If NsLocalizedString finds the strings file, it searches the file for a line that matches the first parameter In the preceding example, NSLocalizedString will search the strings file for the string "First Name" If it doesn’t find a match in the localization project that matches the user's language settings, it will then look for a strings file in the base language and use

Trang 5

the value there If there is no strings file, it will just use the first parameter you passed to the

NSLocalizedString macro

Let’s take a look at this process in action

Real-World iPhone: Localizing Your Application

We're going to create a small application that displays the user’s current locale A locale (an instance of NSLocale) represents both the user’s language and region It is used by the sys- tem to determine what language to use when interacting with the user and to determine how to display dates, currency, and time information, among other things After we create the application, we will then localize it into other languages You'll learn how to localize nib files, string files, images, and even our application's icon You can see what our application is going to look like in Figure 17-1 The name across the top comes from the user’s locale The words down the left side of the view are static labels that are set in the nib file The words down the right side are set programmatically using outlets The flag image at the bottom of the screen is a static UI ImageVi ew

ATT BPM seth ATAT 14:29

English (United States) Deutsch (Deutschland)

Eins

Figure 17-1 The LocalizeMe application shown with three different language/region settings

Let's hop right into it Create a new project in Xcode using the view-based application tem- plate, and call it LocalizeMe If you look in the 17 LocalizeMe folder, you'll see a subfolder named Resources Inside Resources, you'll find a directory named Base Language |n that folder, you'll find two images, icon.png and flag.png Drag both of those to the Resources folder of your project Now, single-click Info.plist, and set the Icon file value to icon.png so that the icon image will be used as your application's icon

Trang 6

We need to create outlets to a total of six labels: one for the blue label across the top of the view and five for the words down the right-hand side Expand the Classes folder, single-click LocalizeMeViewController.h, and make the following changes:

#import <UIKit/UIKit.h>

@interface LocalizeMeViewController : UIViewController {

TBOutlet UILabel *localeLabel;

TBOutlet UTLabel *labell1;

TBOutlet UTLabel *label2;

TBOutlet UTLabel *label3;

TBOutlet UTLabel *label4;

TBOutlet UTLabel *label5;

}

@property Cnonatomic, retain) UILabel *localeLabel ;

@property Cnonatomic, retain) UILabel *labell;

@property Cnonatomic, retain) UILabel *label2;

@property Cnonatomic, retain) UILabel *label3;

@property Cnonatomic, retain) UILabel *label4;

@property Cnonatomic, retain) UILabel *label5;

@end

Now double-click the LocalizeMeViewController.xib file to open the file in Interface Builder Once it’s open, drag a Label from the library, and drop it at the top of the window Resize it

so that it takes the entire width of the view from blue guide line to blue guide line With the label selected, make the text bold using 3B, and change the text alignment to centered and the text color to a bright blue using the attributes inspector

You can also make the font size larger if you wish To do that, select Show Fonts from the Font menu Make the font as large as you like As long as Adjust to fit is selected in the attri- butes inspector, the text will be resized if it gets too long to fit

With your label in place, control-drag from the File’s Owner icon to this new label, and select the localeLabe! outlet

Next, drag five more Labels from the library, and put them against the left margin using the blue guide line, one above the other, as shown in Figure 17-1 Double-click the top one, and change it from Label to One Repeat that step with the other four labels you just added so that they contain the numbers from one to five spelled out

Drag five more Labels from the library, this time placing them against the right margin Change the text alignment using the attributes inspector so that they are right aligned, and increase the size of the label so that it stretches from the right blue guide line to about the middle of the view Control-drag from File’s Owner to each of the five new labels, connecting each one to a different numbered label outlet Now, double-click each one of the new labels, and delete its text We will be setting these values programmatically

Trang 7

Finally, drag an Image View from the library over to the bottom part of the view In the attri- butes inspector, select flag.png for the view's Image attribute, and resize the image to stretch from blue guide line to blue guide line Next, on the attributes inspector, change the Mode attribute from Center to Aspect Fit Not all flags have the same aspect ratio, and we want to make sure the localized versions of the image look right Selecting this option will cause the image view to resize any other images put in this image view so they fit, but it will maintain the correct aspect ratio (ratio of height to width) If you like, make the flag taller, until the sides of the flag touch the blue guide lines

Save and close the nib file, and head back to Xcode Single-click LocalizeMeViewController.m, and make the following changes:

#import "“LocalizeMeViewController.h"

@implementation LocalizeMeViewController

@synthesize localeLabel;

@synthesize labell;

@synthesize label2;

@synthesize label3;

@synthesize label4;

@synthesize label5;

- (void)viewDidLoad {

NSLocale *locale = [NSLocale currentLocale];

NSString *displayNameString = [locale

displayNameForKey:NSLocalelIdentifier

value:[locale localeIdentifier]];

localeLabel.text = displayNameString;

labell.text = NSLocalizedString(@"One", @''The number 1");

label2.text = NSLocalizedString(@"Two", @''The number 2");

label3.text = NSLocalizedString(@"Three", @"The number 3");

label4.text = NSLocalizedString(@"Four", @"The number 4");

label5.text = NSLocalizedString(@"Five", @"The number 5");

[super viewDidLoad];

- (BOOL) shouldAutorotateToInterfaceOrientation:

(UIInterfaceOrientation)interfaceOrientation {

// Return YES for supported orientations

return CinterfaceOrientation == UIInterfaceOrientationPortrait);

Trang 8

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Releases the view if it doesn't have a superview

// Release anything that's not essential, such as cached data

- (void)dealloc {

[localeLabel release];

[labell release];

[label2 release];

[label3 release];

[label4 release];

[label5 release];

[super dealloc];

}

@end

The only thing we need to look at in this class is the vi ewDi dLoad method The first thing we

do there is get an NSLocal1e instance that represents the users’ current locale, which can tell us both their language and their region preferences, as set in their iPhone's Settings application

NSLocale *locale = [NSLocale currentLocale];

Looking at the Current Locale

The next line of code might need a little bit of explanation NsLocale works somewhat like

a dictionary There is a whole bunch of information that it can give us about the current user’s preferences, including the name of the currency they use and the date format they expect You can find a complete list of the values that you can retrieve in the NSLocale API reference

In this next line of code, we’re retrieving the locale identifier, which is the name of

the language and/or region that this locale represents We're using a function called

displayNameForKey: value: The purpose of this method is to return the value of the item we've requested in a specific language

The display name for the French language, for example, would be Francais in French, but French in English This method gives us the ability to retrieve data about any locale so that it can be displayed appropriately to any users In this case, we're getting the display name for the locale in the language of that locale, which is why we pass in [locale localeIdenti fier]

in the second argument The localeIdenti fier is a string in the format we used earlier to create our language projects For an American English speaker, it would be en_US and for

a French speaker from France, it would be fr_FR

NSString *displayNameString = [locale

displayNameForKey:NSLocalelIdenti fier value:[locale localeIdentifier]];

Trang 9

Once we have the display name, we use it to set the top label in the view:

localeLabel.text = displayNameString;

Next, we set the five other labels to the numbers one through five spelled out in our devel- opment base language We also provide a comment telling what each word is You can just pass an empty string if the words are obvious, as they are here, but any string you pass in the second argument will be turned into a comment in the strings file, so you can use this com- ment to communicate with the person doing your translations

labell.text = NSLocalizedString(@"One", @"The number 1");

label2.text = NSLocalizedString(@"Two", @"The number 2");

label3.text = NSLocalizedString(@"Three", @"The number 3");

label4.text = NSLocalizedString(@"Four", @"The number 4");

labelS.text = NSLocalizedString(@"Five", @"The number 5");

Trying Out LocalizeMe

Let’s run our application now You can use either the simulator or a device to test this The simula- tor does seem to cache some language and region settings, so you may want to do this on the device if you have that option Once the application launches, it should look like Figure 17-2

By using the NSLocalizedString macros instead of static strings, we are all ready for local- ization But we are not localized yet If you use the Settings application on the simulator or

on your iPhone to change to

another language or region,

the results would look essen-

view (see Figure 17-3)

aa ATAT > 15:45

francais (France)

Figure 17-2 The language Figure 17-3 The nonlocal- running the base language Our ized application run onan application is set up for localiza- iPhone set to use the French tion but is not yet localized language

Trang 10

OTE

If you run into any problems getting this application to launch, try following the localization steps through the rest of the chapter If that doesn’t help, check our web site at ht tp: //www iphonedevbook com for more suggestions

Localizing the Nib

Now, let's localize the nib file The basic process for localizing any file is the same In Xcode, single-click LocalizeMeViewController.xib, and then press 381 to open the /nfo window for that file If the window is not currently showing the General tab, select the General tab Click the button that says Make File Localizable in the lower-left part of the window (see Figure 17-4)

{ General ~ Targets Comments }

Full Path: /Users/jeff/Desktop/LocalizeMe/LocalizeMeViewController.xib

Path Type: [ Relative to Enclosing Group 4

File Type: ( file.xib req

Mw Include in index

File Encoding: | No Explicit File Encoding

Tab Width: 4 Indent Width: 4

ral Editor uses tabs

yw Editor wraps lines

( Reset to Text Editing Defaults )

( Make File Localizable 3 ( Add Localization )

Figure 17-4 The LocalizeMeViewController.xib Info window

Ngày đăng: 17/10/2013, 20:15

TỪ KHÓA LIÊN QUAN