問題は、言語の変更がバンドルに反映されていないことでした。 したがって、ローカライズされたテキストだけでなく、UIも変更できませんでした。 次のコードを使用してバンドルの設定を変更できます。 次のコードは、実行時に言語を切り替えます。 が蛇腹示すようにNSBundleクラスのサブクラス化する必要があります: - @implementation BundleEx
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
NSBundle *bundle = objc_getAssociatedObject(self, &kBundleKey);
if (bundle) {
return [bundle localizedStringForKey:key value:value table:tableName];
}
else {
return [super localizedStringForKey:key value:value table:tableName];
}
}
@end
@implementation NSBundle (Language)
+ (void)setLanguage:(NSString *)language
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object_setClass([NSBundle mainBundle], [BundleEx class]);
});
BOOL appleTextDirection = NO;
BOOL rightToLeftWritingDirection = NO;
if ([language isEqual:@"ar"]) {
rightToLeftWritingDirection =YES;
appleTextDirection = NO;
if ([[[UIView alloc] init] respondsToSelector:@selector(setSemanticContentAttribute:)]) {
[[UIView appearance] setSemanticContentAttribute:
UISemanticContentAttributeForceRightToLeft];
}
}else {
rightToLeftWritingDirection =NO;
appleTextDirection = YES;
if ([[[UIView alloc] init] respondsToSelector:@selector(setSemanticContentAttribute:)]) {
[[UIView appearance] setSemanticContentAttribute:UISemanticContentAttributeForceLeftToRight];
}
}
[[NSUserDefaults standardUserDefaults] setBool:appleTextDirection forKey:@"AppleTextDirection"];
[[NSUserDefaults standardUserDefaults] setBool:rightToLeftWritingDirection forKey:@"NSForceRightToLeftWritingDirection"];
[[NSUserDefaults standardUserDefaults] synchronize];
id value = language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil;
objc_setAssociatedObject([NSBundle mainBundle], &kBundleKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
トグルするために使用されるコード: -
-(void)toggleTheLanguageWith:(NSString *)identifier{
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray* languages = [userDefaults objectForKey:@"AppleLanguages"];
NSString *language = nil;
if ([[languages objectAtIndex:0] rangeOfString:@"en"].location != NSNotFound) {
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"ar",@"en",nil] forKey:@"AppleLanguages"];
language = @"ar";
}else if ([[languages objectAtIndex:0] rangeOfString:@"ar"].location != NSNotFound) {
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en",@"ar", nil] forKey:@"AppleLanguages"];
language = @"en";
}
[[NSUserDefaults standardUserDefaults]synchronize];
[NSBundle setLanguage:language];
UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
self.window.rootViewController = [mystoryboard instantiateViewControllerWithIdentifier:identifier];
[self.window makeKeyAndVisible];
[UIView transitionWithView:self.window duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
} completion:^(BOOL finished) {
}];
}