I have following code to switch language runtime:
-(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 localised 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];
}
This is working. My storyboards are also localised, but they are not changing when I switch to another language.
How can I get localised values for the storyboard strings?
Changing the Language at run time is a bit tricky.
This is the best way I've used to do so with the help of 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
When 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];
When you want to set a string:
[self.someButton setTitle:[Language get:@"Some Button Text" alter:nil] forState:UIControlStateNormal];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With