문제는 언어 변경이 번들에 반영되지 않았기 때문입니다. 그래서 현지화 된 텍스트뿐만 아니라 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) {
}];
}
을