How can I change the language setting in my application?
I need to add language setting functionality to the project.
How can I change the language setting in my application?
I need to add language setting functionality to the project.
Try this :
// reading the language from the preferredLanguages in the bundle project architecture.
#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]
#define CurrentNSLocalizedString(key) NSLocalizedStringFromTableInBundle(key, nil, currentLanguageBundle, @"")
// you can set language in the same location preferred settings like this :
[[NSUserDefaults standardUserDefaults]setObject:lang forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
// lang can be :
@"fr"
@"en"
@"de"
@"es"
@"it"
// etc ...
then you can call traduction of string configured on Localizable.Strings like this : CurrentNSLocalizedString(@"my_text")
And here are some links to use your Strings translations : https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPInternational/LocalizingYourApp/LocalizingYourApp.html
https://www.raywenderlich.com/64401/internationalization-tutorial-for-ios-2014
If you wish to change the language setting in your application. There are 2 solutions for consideration.
The first one is forcing the main bundle to load a specific locale source
.h
@interface NSBundle (HLanguage)
+(void)setLanguage:(NSString*)language;
@end
.m
#import "NSBundle+HLanguage.h"
#import <objc/runtime.h>
static const char _bundle=0;
@interface HBundle : NSBundle
@end
@implementation HBundle
-(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
NSBundle* bundle=objc_getAssociatedObject(self, &_bundle);
return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end
@implementation NSBundle (HLanguage)
+(void)setLanguage:(NSString*)language
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
{
object_setClass([NSBundle mainBundle],[HBBundle class]);
});
objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
This approach is a good and simple way, as you just add any supported localizations.
The second one is more flexible and allows you to support either language setting or contents driven, for example, with the same Eng locale, however, you want English in Germany will show the different content with English in Singapore. To put it simply, you create your own bundle resource, put all supported languages, then use NSLocalizedStringWithDefaultValue
or NSLocalizedStringFromTableInBundle
to specify "bundle" and "table" of the selected language.
Hope this would be helpful.