Requirements Description: The application has a button inside, click Switch language (such as Chinese and English toggle).
Said this is a long time ago to do a function point, the beginning is no clue, and later solved the discovery is very simple, the method to share.
1. Principle.
View the definition of nslocalizedstring (@ "abc", nil);
?
1 2 |
#define NSLOCALIZEDSTRING (key, comment) \          [[ Code class= "OBJC keyword" >nsbundle mainbundle] Localizedstringforkey: (key) value:@ table: nil |
Then think about why this definition will be located in the current system default language corresponding to the strings file?
If this is the case, then the problem is solved, isn't it?
2. Specific analysis
Redefine nslocalizedstring.
?
1 2 3 |
#define AppLanguage @"appLanguage" #define CustomLocalizedString(key, comment) \ [[ nsbundle Code class= "OBJC plain" >bundlewithpath:[[ nsbundle mainbundle] pathforresource:[ nsstring stringwithformat:@ ,[[ nsuserdefaults standarduserdefaults] objectforkey:@ "Applanguage" ]] oftype:@ Code class= "OBJC string" > "lproj" ] "Localizedstringforkey: (key) value:@ table: nil |
You don't have to explain, do you? Find the corresponding strings file.
3. Usage
?
1 2 3 4 |
if (![[ NSUserDefaults standardUserDefaults]objectForKey:AppLanguage]) { [[ NSUserDefaults standardUserDefaults] setObject:@ "zh-Hans" forKey:AppLanguage]; } label.text= CustomLocalizedString(@ "sub_menu_download" , nil ); //@"离线下载"; |
4. Toggle
When you click the toggle button in English,
?
1 2 3 4 5 6 7 8 |
NSString *currentLanguage = [[ NSUserDefaults standardUserDefaults]objectForKey:AppLanguage]; if ([currentLanguage isEqualToString: @ "en" ]) { [[ NSUserDefaults standardUserDefaults] setObject:@ "zh-Hans" forKey:AppLanguage]; } else { [[ NSUserDefaults standardUserDefaults] setObject:@ "en" forKey:AppLanguage]; } [[ NSUserDefaults standardUserDefaults] synchronize]; |
The program also has to do further interface-related processing, such as Tabbar re-initialization and so on
Multi-language free switching within iOS development app