Skip to content

Instantly share code, notes, and snippets.

@ChrisChares
Last active September 16, 2019 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisChares/f53c8f1a509649e4ad57 to your computer and use it in GitHub Desktop.
Save ChrisChares/f53c8f1a509649e4ad57 to your computer and use it in GitHub Desktop.
Runtime language localization in Objective C
//example of setting run time languages in obj-c
//note that this won't redraw the layout on language change, you have to do that manually
//based on this stack overflow answer: http://stackoverflow.com/a/23395903/1226668
#import <Foundation/Foundation.h>
#define RUNTIME_LANGUAGE_STORAGE @"runtimeLanguageStorage"
#define RunTimeLanguageEnglish @"en"
#define RunTimeLanguageSpanish @"es"
#undef NSLocalizedString
#define NSLocalizedString(key, comment) [[NSBundle mainBundle] runTimeLocalizedStringForKey:(key) value:@"" table:nil]
#define setLanguage(x) [[NSUserDefaults standardUserDefaults] setObject:x forKey:RUNTIME_LANGUAGE_STORAGE]; [[NSUserDefaults standardUserDefaults] synchronize];
@interface NSBundle (RunTimeLanguage)
- (NSString *)runTimeLocalizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName;
@end
#import "NSBundle+RunTimeLanguage.h"
@implementation NSBundle (RunTimeLanguage)
- (NSString *)runTimeLocalizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName {
NSString *languageCode = [[NSUserDefaults standardUserDefaults] objectForKey:RUNTIME_LANGUAGE_STORAGE];
if ( languageCode == nil ) {
languageCode = @"en";
}
NSString *path= [[NSBundle mainBundle] pathForResource:languageCode ofType:@"lproj"];
NSBundle *languageBundle = [NSBundle bundleWithPath:path];
NSString *localizedString=[languageBundle localizedStringForKey:key value:key table:nil];
return localizedString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment