Last active
September 16, 2019 23:29
-
-
Save ChrisChares/f53c8f1a509649e4ad57 to your computer and use it in GitHub Desktop.
Runtime language localization in Objective C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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