How to get localized storyboard lines after switching to language at runtime in iOS?

I have the following code to switch the runtime of the language:

-(void) switchToLanguage:(NSString *)lang{ self.language = lang; [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:self.language, nil] forKey:@"AppleLanguages"]; [[NSUserDefaults standardUserDefaults] synchronize]; } 

And I have a helper function that retrieves localized strings:

 +(NSString *) getLocalizedString:(NSString *)key{ AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:appDelegate.language]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; return [dict objectForKey:key]; } 

It works. My storyboards are also localized, but they do not change when switching to another language.

How to get localized values ​​for storyboard lines?

+5
source share
1 answer

Changing the language at runtime is a bit more complicated.

This is the best way I've used for this tiny class:

Language.m:

 #import "Language.h" @implementation Language static NSBundle *bundle = nil; +(void)initialize { NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; NSArray* languages = [defs objectForKey:@"AppleLanguages"]; NSString *current = [languages objectAtIndex:0]; [self setLanguage:current]; } +(void)setLanguage:(NSString *)l { NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ]; bundle = [NSBundle bundleWithPath:path]; } +(NSString *)get:(NSString *)key alter:(NSString *)alternate { return [bundle localizedStringForKey:key value:alternate table:nil]; } @end 

Language.h:

 import <Foundation/Foundation.h> @interface Language : NSObject +(void)setLanguage:(NSString *)l; +(NSString *)get:(NSString *)key alter:(NSString *)alternate; @end 

If you want to change the language:

 [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", @"de", nil] forKey:@"AppleLanguages"]; [[NSUserDefaults standardUserDefaults] synchronize]; [Language setLanguage:@"en"]; [(AppDelegate *)[[UIApplication sharedApplication] delegate] window].rootViewController = [self.storyboard instantiateInitialViewController]; 

If you want to set the line:

 [self.someButton setTitle:[Language get:@"Some Button Text" alter:nil] forState:UIControlStateNormal]; 
+2
source

Source: https://habr.com/ru/post/1205231/


All Articles