IOS applications are internationalized and do not follow the system language

Source: Internet
Author: User

There are many articles on iOS internationalization on the Internet, but they are basically based on the internationalization of the following system language. I will not repeat them here-0-

Today, we will talk about the language version scheme that does not follow the system's switch language version scheme, that is, the switch language version scheme within the program.


The internal language of the application does not follow the system language and is controlled by the application itself. By configuring multiple language files, the application dynamically obtains the language files in different folders based on the user's selection and displays them on the interface.

At last, the user-selected language is persistently stored locally and read at the next runtime.


1. Create a project

Create a Single View Application project named MyInternational.


2. Add multi-language files

We choose to use our own language file instead of the system's localizable. string, because when svn is used for project development, operations on the same file by multiple people may cause conflicts.

Add a new Strings File to Resource:


Name "hello" (remember to check the project in Targets)



After the new file is created, the hello. string file is generated and dragged into Supporting Files.


3. Configure hello. string to internationalize

Configure the hello. string file.

Click the hello. strings file and click Make localized (localization) in the circle ).


Only English. Click OK.



4. Internationalization of configuration items

Many configuration methods on the network are unreliable, because the new version of Xcode is replaced by the "+" position. Here we will teach you the correct method, click "Project"> "select Project"> "Info"> "+.


Click "+" to add Chinese characters. Of course, you can also add other languages. In the pop-up dialog box, infoPlist is an international file for configuring the system, and you can configure multilingual environments such as icons, not in the scope of this article. The configuration is required for the nib file.



After the configuration is complete, the hello. string file is divided into two files.

After completing the above four steps, the multi-language environment configuration in the project is completed. Let's take a look at how to write the code.


5. Add the required string

Add strings of the corresponding language in hello. strings (English) and hello. strings (Chinese) respectively.

String format: "key" = "value"; key-value Pair (do not forget the semicolon !)

Next, configure the string required by the project, one for lable display and one for button display.

 

Hello. strings (English)

 

Hello. strings (Chinese)

 

6. Check the process.

[Implementation ideas :]

When initializing the first Controller, load the application language. If the userLanguage (in-app language) does not exist during the first loading, save it to userlanguage in the current system language and read it directly next time. After reading the file, get the corresponding file path, get the file index, and store it in the static variable bundle of the tool class InternationalControl.

When strings are needed elsewhere, get bundle using the tool class to read the strings in the corresponding file.


7. Create a tool class InternationalControl


InternationalControl. h

# Import <Foundation/Foundation. h> # import <UIKit/UIKit. h> @ interface InternationalControl: NSObject + (NSBundle *) bundle; // obtain the current resource file + (void) initUserLanguage; // initialize the language file + (NSString *) userLanguage; // obtain the current language of the application + (void) setUserlanguage :( NSString *) language; // set the current language @ end

InternationalControl. m

1) create a static variable bundle and obtain the method bundle (Note: Do not use getBundle here ).

static NSBundle *bundle = nil;+ ( NSBundle * )bundle{        return bundle;}

The userLanguage is stored in NSUserDefaults. When loading for the first time, check whether it exists. If it does not exist, read AppleLanguages and assign it to userLanguage.
+ (Void) initUserLanguage {NSUserDefaults * def = [NSUserDefaults standardUserDefaults]; NSString * string = [def valueForKey: @ "userLanguage"]; if (string. length = 0) {// obtain the current language version of the system (Chinese zh-Hans, English en) NSArray * ages = [def objectForKey: @ "AppleLanguages"];
NSString * current = [ages objectAtIndex: 0]; string = current; [def setValue: current forKey: @ "userLanguage"]; [def synchronize]; // persistence, if this parameter is not added, the file will not be saved.} // obtain the file path NSString * path = [[NSBundle mainBundle] pathForResource: string ofType: @ "lproj"]; bundle = [NSBundle bundleWithPath: path]; // generate bundle}

+(NSString *)userLanguage{        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];        NSString *language = [def valueForKey:@"userLanguage"];        return language;}

+ (Void) setUserlanguage :( NSString *) language {NSUserDefaults * def = [NSUserDefaults standardUserDefaults]; // 1. step 1: Change the bundle value NSString * path = [[NSBundle mainBundle] pathForResource: language ofType: @ "lproj"]; bundle = [NSBundle bundleWithPath: path]; // 2. persistence [def setValue: language forKey: @ "userLanguage"]; [def synchronize];}

8. Drag nib and configure click events

A button, a label, and a button are used to switch languages. label is used to display information.


9. Configure the first Controller to be loaded. Here is YGViewController.

YGViewController. h

# Import <UIKit/UIKit. h> @ interface YGViewController: UIViewController @ property (retain, nonatomic) IBOutlet UILabel * inviteLabel; // label-(IBAction) changeLanguage :( id) sender; // click the event @ property (retain, nonatomic) IBOutlet UIButton * btChange; // button @ end


YGViewController. m

1) load:

-(Void) viewDidLoad {// register a notification to receive a notification of language change [[nsicationicationcenter defaultCenter] addObserver: self selector: @ selector (changeLanguage) name: @ "changeLanguage" object: nil]; [InternationalControl initUserLanguage]; // initialization application language NSBundle * bundle = [InternationalControl bundle]; NSString * inviteMsg = [bundle localizedStringForKey: @ "invite" value: nil table: @ "hello"]; NSString * buttonInfo = [bundle localizedStringForKey: @ "buttonInfo" value: nil table: @ "hello"]; // The table is hello. string file name [_ btChange setTitle: buttonInfo forState: UIControlStateNormal]; _ inviteLabel. text = inviteMsg; [super viewDidLoad];}

-(IBAction) changeLanguage :( id) sender {NSString * lan = [InternationalControl userLanguage]; if ([lan isEqualToString: @ "en"]) {// judge the current language, change [InternationalControl setUserlanguage: @ "zh-Hans"];} else {[InternationalControl setUserlanguage: @ "en"];} // send a notification after the change is complete, after the modification is completed, the system prompts you to refresh the interface [[NSNotificationCenter defacenter center] postNotificationName: @ "changeLanguage" object: nil];}.

-(void)changeLanguage{        [_btChange setTitle:[[InternationalControl bundle] localizedStringForKey:@"buttonInfo" value:nil table:@"hello"] forState:UIControlStateNormal];        _inviteLabel.text =[[InternationalControl bundle] localizedStringForKey:@"invite" value:nil table:@"hello"];}

10. Running Interface


You can see that the language switch is successful after you click to switch the language.

Exit the program and enter again. The last selected language is retained.

 

Http://blog.csdn.net/yang8456211/article/details/12031667


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.