我有以下代码来切换语言运行时:
-(void) switchToLanguage:(NSString *)lang{
self.language = lang;
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:self.language, nil]
forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
我有一个Helper函数可以检索本地化的字符串:
+(NSString *) getLocalizedString:(NSString *)key{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Localizable"
ofType:@"strings"
inDirectory:nil
forLocalization:appDelegate.language];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return [dict objectForKey:key];
}
这很有效。我的故事板也是本地化的,但是当我切换到另一种语言时它们没有改变。
如何获取故事板字符串的本地化值?
答案 0 :(得分:2)
在运行时更改语言有点棘手。
这是我在这个小班的帮助下用来做的最佳方式:
<强> Language.m:强>
#import "Language.h"
@implementation Language
static NSBundle *bundle = nil;
+(void)initialize {
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString *current = [languages objectAtIndex:0];
[self setLanguage:current];
}
+(void)setLanguage:(NSString *)l
{
NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
bundle = [NSBundle bundleWithPath:path];
}
+(NSString *)get:(NSString *)key alter:(NSString *)alternate
{
return [bundle localizedStringForKey:key value:alternate table:nil];
}
@end
<强> Language.h:强>
import <Foundation/Foundation.h>
@interface Language : NSObject
+(void)setLanguage:(NSString *)l;
+(NSString *)get:(NSString *)key alter:(NSString *)alternate;
@end
如果您想更改语言:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", @"de", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
[Language setLanguage:@"en"];
[(AppDelegate *)[[UIApplication sharedApplication] delegate] window].rootViewController = [self.storyboard instantiateInitialViewController];
如果要设置字符串:
[self.someButton setTitle:[Language get:@"Some Button Text" alter:nil] forState:UIControlStateNormal];