iOS development-Multi-lingual localization and manual switching

Source: Internet
Author: User


The app needs to be available for international promotion and multilingual support. It can be implemented by localizing the language and switching. This project can not switch the system language, do not restart the application to switch the custom language directly. Now it is only written in Chinese and English, and other languages are treated the same way. If the support language is many, the switching time will not take a long time, switch successfully.



1. Create a project





2. Configure project localization support Simplified Chinese and English


Project-project-info->localizations, click "+", select (Chinese (Simplified)) Add Simplified Chinese, English Xcode comes with (中文版), so do not need to add again.








3. Add Multilingual Files


1> We choose to use our own language files, so we want to create a suffix. strings file;
2>: You need to be able to switch languages manually, instead of changing according to the system language, so the naming cannot be localizable.strings;
3>. The file is named Language.strings (name it yourself, suffix:. Strings) (Remember targets to tick the item).







4. Configure language.strings localization, support Simplified Chinese and English.


1> Select the Language.strings file to view the right sidebar information for Xcode;
2>. Click the localize in localization ... button
3>: Select Base or Chinese or English and then localize;
4>: Check Chinese and English, base item is optional, choose Usefile.










At this time language.strings will be more than two sub-files, respectively, in English and Simplified Chinese.

You will also see two folders En.lproj and Zh-hans.lproj in the Project project folder.

These two folders do not copy other items, because these two files are associated with the project engineering files, directly copied over will not read the inside of the. strings file. Of course, it is possible to copy the contents directly.






5. Add and refine all text that needs to be converted in language.strings


1. Each field is separated by a semicolon, because it is not an OC file, so you do not need to use @ to denote strings;
2. "Key" = "value", key can be in Chinese, also can be useful in English, performance has no difference to see.






</pre><pre name= "code" class= "OBJC" >//english "top" = "top"; " Middle "=" middle ";" Bottom "=" bottom ";" Left "=" left ";" Right "=" right ";" Enter "=" enter ";" Cancel "=" Cancel ";" Language "=" 中文版 ";" Back "=" back ";" Change "=" Change Language ";


Simplified Chinese "top" = "upper"; " Middle "=" middle ";" Bottom "=" bottom ";" Left "=" to "LH"; " Right "="; Enter "=" OK ";" Cancel "=" Cancel ";" Language "=" Chinese ";" Back "=" return ";" Change "=" Modify language ";


6. Write a PCH macro definition


Used to read language files and return value values. After all, there will be multiple files in a project, so use PCH

Set up PCH, double-click on targets-build Settings-Apple LLVM Language-Prefixheader to fill in the project name/pch file name (e.g., iOS multilingual localization and switching/prefixheader.pch )











In the PCH, enter

/* Get the local language currently saved in Nsuserdefaults #define Currentlanguage [nsstring stringwithformat:@ "%@", [[Nsuserdefaults  standarduserdefaults]objectforkey:@ "Applanguage"]] based on getting the language file, the path file name type is Lproj, which is the. lproj folder.  Zh-hans.lproj and En.loproj exist nsuserdefaults suitable, the Chinese and English respectively set Zh-hans and EN, can not be changed. #define LANGUAGEPATH [[NSBundle Mainbundle] pathforresource:currentlanguage oftype:@ "lproj"] get return conversion results based on key value Language for language file name language.string #define Localized (key) [[NSBundle Bundlewithpath:languagepath] Localizedstringforkey :(key) Value:nil table:@ "Language"] *///equivalent to the three macros defined above definition localized (key) [[NSBundle Bundlewithpath:[[nsbundle Mainbundle] pathforresource:[nsstring stringwithformat:@ "%@", [[Nsuserdefaults Standarduserdefaults] objectForKey:@ "Applanguage"]] oftype:@ "Lproj"] Localizedstringforkey: (key) Value:nil table:@ "Language"]//<span style= " Font-family:arial, Helvetica, Sans-serif; >language must be the same as the strings file name created </span>





Attention:



7. Save the currently used language to Nsuserdefaults (add Refresh Page method)

1> in AppDelegate.h declaration of a method to refresh the page, the internal implementation

2> In the appdelegate.m file didfinishlaunchingwithoptions gets the current phone language and stores it to nsuserdefaults.

#import "AppDelegate.h" #import "ViewController.h" @interface appdelegate () @end @implementation appdelegate-(BOOL)    Application: (uiapplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {//Add Nav        [Self MAINVC];    Gets the current phone language, stored to nsuserdefaults. if (![ [Nsuserdefaults standarduserdefaults]objectforkey:@ "Applanguage"]) {Nsarray *languages = [NSLocale preferr        Edlanguages];        NSString *language = [languages objectatindex:0]; if ([Language hasprefix:@ "Zh-hans"]) {//Start match [[Nsuserdefaults Standarduserdefaults] setobject:@ "Zh-hans" Forkey        : @ "Applanguage"];        }else{[[Nsuserdefaults standarduserdefaults] setobject:@ "en" forkey:@ "applanguage"]; }} return YES; Declare in. h-(void) mainvc{uinavigationcontroller *nav = [[Uinavigationcontroller alloc]initwithrootviewcontroller:[    Viewcontroller New]];    Self.window.rootViewController = nav; }






8. Create and initialize a UI control


1>. Create and initialize Uilabel in VIEWCONTROLLER.M to display multilingual text, UIButton toggle language buttons and respond to events.
Read gets the return value according to the language file key value, using the method: Localized (key). 2>. Jump page Implementation Change language

#import "ViewController.h" #import "SecondViewController.h" @interface Viewcontroller () @end @implementation        viewcontroller-(void) viewdidload {[Super viewdidload];    UILabel *lable = [[UILabel alloc]initwithframe:cgrectmake (0, 200)];    Lable.backgroundcolor = [Uicolor Grouptableviewbackgroundcolor];    Lable.text = [NSString stringwithformat:@ "%@------%@", Localized (@ "Top"), Localized (@ "bottom")];    Lable.textcolor = [Uicolor blackcolor];    Lable.textalignment = Nstextalignmentcenter;            [Self.view addsubview:lable];    UIButton *btn = [UIButton buttonwithtype:uibuttontyperoundedrect];    Btn.frame = CGRectMake (0, Cgrectgetmaxy (lable.frame) +100, Self.view.frame.size.width, 200);    Btn.backgroundcolor = [Uicolor Lightgraycolor];    [btn Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];    [Btn settitle:[nsstring stringwithformat:@ "%@", Localized (@ "Change")] forstate:uicontrolstatenormal]; [Btn addtarget:self Action:@sElector (Btnclick) forcontrolevents:uicontroleventtouchupinside];        [Self.view ADDSUBVIEW:BTN]; }-(void) btnclick{[Self.navigationcontroller pushviewcontroller:[secondviewcontroller new] animated:YES];}




9. Add a notification hub (on the second page)

1. Because it is to refresh all attempts, all previous attempts are reinitialized and need to be reset Window.rootviewcontroller

2. In order to stop repeating the code, call Appdelegate's Tomain method directly, to set the Rootviewcontroller

Respond to events when receiving notifications, and can also be used without notification to add language switching operations directly to the button click event.


#import "SecondViewController.h" #import "AppDelegate.h" #define languagechanged   @ "Language_change_notification "@interface Secondviewcontroller () @end @implementation secondviewcontroller-(void) Viewwillappear: (BOOL) animated{    [Super viewwillappear:animated];    Add notification hubs, monitor language changes    [[nsnotificationcenter defaultcenter] addobserver:self selector: @selector (languagechanged) Name:languagechanged Object:nil];    } -(void) Viewwilldisappear: (BOOL) animated{    [Super viewwilldisappear:animated];    Remove notification hubs    [[Nsnotificationcenter defaultcenter] removeobserver:self name:languagechanged object:nil];} KVO Jump-(void) languagechanged{    appdelegate *appdelegate = (appdelegate *) [uiapplication sharedapplication]. delegate;    [Appdelegate MAINVC];}







10. Adding a toggle language event
UIButton Toggle Language buttons and response events.
Modify a locally acquired language file-alternate
-(void) viewdidload {[Super viewdidload];    Self.title = localized (@ "Middle"); Uibarbuttonitem *left = [[Uibarbuttonitem alloc]initwithtitle:localized (@ "back") style:uibarbuttonitemstyleplain    Target:self Action: @selector (back)];            Self.navigationItem.leftBarButtonItem = left;    UIButton *btn = [UIButton buttonwithtype:uibuttontyperoundedrect];    Btn.frame = CGRectMake (0, 100, 375, 200);    Btn.backgroundcolor = [Uicolor Lightgraycolor];    [btn Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];    [Btn settitle:[nsstring stringwithformat:@ "%@", Localized (@ "language")] forstate:uicontrolstatenormal];    [Btn addtarget:self Action: @selector (Btnclick) forcontrolevents:uicontroleventtouchupinside];        [Self.view ADDSUBVIEW:BTN]; }-(void) back{[Self.navigationcontroller Poptorootviewcontrolleranimated:yes];} -(void) btnclick{Uialertcontroller *alert =[uialertcontroller alertcontrollerwithtitle:localized (@ "Chenge") message : Nil PreferredstylE:uialertcontrollerstylealert]; Uialertaction *left = [uialertaction actionwithtitle:localized (@ "Cancel") Style:uialertactionstylecancel Handler:nil    ]; Uialertaction *right = [uialertaction actionwithtitle:localized (@ "enter") Style:uialertactionstyledefault handler:^ (            Uialertaction * _nonnull action) {[Self enterclick];    }];    [Alert Addaction:left];    [Alert Addaction:right]; [Self Presentviewcontroller:alert animated:yes completion:nil];} -(void) enterclick{//modify locally acquired language files--alternate NSString *language = [[Nsuserdefaults Standarduserdefaults]objectforke    y:@ "Applanguage"]; if ([Language isequaltostring: @ "en"]) {[[Nsuserdefaults standarduserdefaults] setobject:@ "Zh-hans" forkey:@ "AppLa    Nguage "];    }else {[[Nsuserdefaults standarduserdefaults] setobject:@ "en" forkey:@ "applanguage"];    } [[Nsuserdefaults standarduserdefaults] synchronize]; [[Nsnotificationcenter Defaultcenter] postnotificationname:languagechanged obJect:nil]; }





This demo: http://download.csdn.net/detail/jackjia2015/9411833


iOS development-Multi-lingual localization and manual switching

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.