如何在IOS中运行时切换到语言后获取本地化的故事板字符串?

时间:2014-10-21 21:11:24

标签: ios localization

我有以下代码来切换语言运行时:

-(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];
}

这很有效。我的故事板也是本地化的,但是当我切换到另一种语言时它们没有改变。

如何获取故事板字符串的本地化值?

1 个答案:

答案 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];