Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get localised storyboard strings after switching to language at runtime in IOS?

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?

like image 211
Burak Avatar asked Oct 31 '22 15:10

Burak


1 Answers

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];
like image 193
Segev Avatar answered Nov 14 '22 09:11

Segev