【问题标题】:iOS: How to change app language programmatically WITHOUT restarting the app?iOS:如何在不重新启动应用程序的情况下以编程方式更改应用程序语言?
【发布时间】:2012-03-14 02:05:15
【问题描述】:

当我在设备语言上独立更改应用程序使用的语言时,在我关闭应用程序并重新启动它之前它不会生效。如何根据所选语言不要求重新启动应用程序以再次加载所有 nib 文件和 .strings 文件?

我使用它在运行时更改语言:

NSArray* languages = [NSArray arrayWithObjects:@"ar", @"en", nil]; 
[[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"];

【问题讨论】:

标签: ios localization


【解决方案1】:

这对我有用: 斯威夫特 4:

创建一个名为 BundleExtension.swift 的文件,并在其中添加以下代码 -

var bundleKey: UInt8 = 0

class AnyLanguageBundle: Bundle {

override func localizedString(forKey key: String,
                              value: String?,
                              table tableName: String?) -> String {

    guard let path = objc_getAssociatedObject(self, &bundleKey) as? String,
        let bundle = Bundle(path: path) else {

            return super.localizedString(forKey: key, value: value, table: tableName)
    }

    return bundle.localizedString(forKey: key, value: value, table: tableName)
  }
}

extension Bundle {

class func setLanguage(_ language: String) {

    defer {

        object_setClass(Bundle.main, AnyLanguageBundle.self)
    }

    objc_setAssociatedObject(Bundle.main, &bundleKey,    Bundle.main.path(forResource: language, ofType: "lproj"), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  }
}

现在,当您需要更改语言时,请调用此方法:

func languageButtonAction() {
    // This is done so that network calls now have the Accept-Language as "hi" (Using Alamofire) Check if you can remove these
    UserDefaults.standard.set(["hi"], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()

    // Update the language by swaping bundle
    Bundle.setLanguage("hi")

    // Done to reintantiate the storyboards instantly
    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateInitialViewController()
}

【讨论】:

  • 又好又干净!
  • 如何使当前视图控制器重新加载以查看语言更改而不是导航到根视图控制器? @ankit
  • 完美答案!
  • 完美!您应该将“让故事板...”部分添加到最后的 setLanguage 函数中。
  • 键盘工具栏本地化没有改变
【解决方案2】:

我对带有选项卡式导航的 Kiosk 模式 iPad 应用程序有类似的要求。该应用程序不仅需要支持即时语言更改,而且必须知道大多数选项卡已经从 nib 加载,因为该应用程序仅在大约每周一次(平均)重新启动时,当一个新的版本已加载。

我尝试了几个建议来利用现有的 Apple 本地化机制,但它们都有严重的缺点,包括 XCode 4.2 中对本地化 nib 的支持不可靠——我的 IBoutlet 连接变量似乎在 IB 中设置正确,但在运行时它们会经常为空!?

我最终实现了一个模仿 Apple NSLocalizedString 类但可以处理运行时更改的类,并且每当用户进行语言更改时,我的类都会发布通知。需要本地化字符串(和图像)来更改的屏幕声明了一个 handleLocaleChange 方法,该方法在 viewDidLoad 处调用,并且在发布 LocaleChangedNotification 时调用。

我的所有按钮和图形都设计为独立于语言,尽管标题文本和标签文本通常会根据区域设置进行更新。如果我必须更改图像,我想我可以在每个屏幕的 handleLocaleChange 方法中这样做。

这里是代码。它包括对 nib/bundle 路径的一些支持,而我在最终项目中实际上并没有使用这些路径。

MyLanguage.h // // MyLanguage.h // //

#import <Foundation/Foundation.h>

#define DEFAULT_DICTIONARY_FOR_STRINGS                      @""
#define ACCESSING_ALTERNATE_DICTIONARY_SETS_DEFAULT         1

#define LANGUAGE_ENGLISH_INT  0
#define LANGUAGE_SPANISH_INT  1
#define LANGUAGE_ENGLISH_SHORT_ID  @"en"
#define LANGUAGE_SPANISH_SHORT_ID  @"es"

#define LANGUAGE_CHANGED_NOTIFICATION   @"LANGUAGE_CHANGED"


@interface MyLanguage : NSObject
{
    NSString        *currentLanguage;    
    NSDictionary    *currentDictionary;
    NSBundle        *currentLanguageBundle;
}

+(void) setLanguage:(NSString *)languageName;


+(NSString *)stringFor:(NSString *)srcString forLanguage:(NSString *)languageName;
+(NSString *)stringFor:(NSString *)srcString;

+ (MyLanguage *)singleton;

@property (nonatomic, retain) NSBundle        *currentLanguageBundle;
@property (nonatomic, retain) NSString        *currentLanguage;    
@property (nonatomic, retain) NSDictionary    *currentDictionary;

@end

MyLanguage.m: // // MyLanguage.m

#import "MyLanguage.h"
#import "Valet.h"

#define GUI_STRING_FILE_POSTFIX   @"GUIStrings.plist"

@implementation MyLanguage

@synthesize currentLanguage;   
@synthesize currentDictionary;
@synthesize currentLanguageBundle;

+(NSDictionary *)getDictionaryNamed:(NSString *)languageName
{
    NSDictionary *results = nil;

    // for now, we store dictionaries in a PLIST with the same name.
    NSString *dictionaryPlistFile = [languageName stringByAppendingString:GUI_STRING_FILE_POSTFIX];

    NSString *plistBundlePath = [Valet getBundlePathForFileName:dictionaryPlistFile];

    if ( [[NSFileManager defaultManager] fileExistsAtPath:plistBundlePath] )
    {
        // read it into a dictionary
        NSDictionary *newDict = [NSDictionary dictionaryWithContentsOfFile:plistBundlePath]; 
        results = [newDict valueForKey:@"languageDictionary"];

    }// end if

    return results;
}

+(NSString *)stringFor:(NSString *)srcString forDictionary:(NSString *)languageName;
{
    MyLanguage *gsObject = [MyLanguage singleton];

    // if default dictionary matches the requested one, use it.
    if ([gsObject.currentLanguage isEqualToString:languageName])
    {
        // use default
        return [MyLanguage stringFor:srcString];
    }// end if
    else
    {
        // get the desired dictionary
        NSDictionary *newDict = [MyLanguage getDictionaryNamed:languageName];

        // default is not desired!
        if (ACCESSING_ALTERNATE_DICTIONARY_SETS_DEFAULT)
        {
            gsObject.currentDictionary = newDict;
            gsObject.currentLanguage = languageName;
            return [MyLanguage stringFor:srcString];
        }// end if
        else
        {
            // use current dictionary for translation.
            NSString *results = [gsObject.currentDictionary valueForKey:srcString];

            if (results == nil)
            {
                return srcString;
            }// end if

            return results;
        }
    }

}

+(void) setLanguage:(NSString *)languageName;
{
    MyLanguage *gsObject = [MyLanguage singleton];

    // for now, we store dictionaries in a PLIST with the same name.
    // get the desired dictionary
    NSDictionary *newDict = [MyLanguage getDictionaryNamed:languageName];

    gsObject.currentDictionary = newDict;
    gsObject.currentLanguage = languageName;   


    // now set up the bundle for nibs
    NSString *shortLanguageIdentifier = @"en";
    if ([languageName contains:@"spanish"] || [languageName contains:@"espanol"] || [languageName isEqualToString:LANGUAGE_SPANISH_SHORT_ID])
    {
        shortLanguageIdentifier = LANGUAGE_SPANISH_SHORT_ID;
    }// end if
    else
        shortLanguageIdentifier = LANGUAGE_ENGLISH_SHORT_ID;

//    NSArray *languages = [NSArray arrayWithObject:shortLanguageIdentifier];
//    [[NSUserDefaults standardUserDefaults] setObject:languages forKey:@"AppleLanguages"]; 
//    
    NSString *path= [[NSBundle mainBundle] pathForResource:shortLanguageIdentifier ofType:@"lproj"];
    NSBundle *languageBundle = [NSBundle bundleWithPath:path];
    gsObject.currentLanguageBundle = languageBundle;


    [[NSNotificationCenter defaultCenter] postNotificationName:LANGUAGE_CHANGED_NOTIFICATION object:nil];

}


+(NSString *)stringFor:(NSString *)srcString;
{
    MyLanguage *gsObject = [MyLanguage singleton];
    // default is to do nothing.
    if (gsObject.currentDictionary == nil || gsObject.currentLanguage == nil || [gsObject.currentLanguage isEqualToString:DEFAULT_DICTIONARY_FOR_STRINGS] )
    {
        return srcString;
    }// end if

    // use current dictionary for translation.
    NSString *results = [gsObject.currentDictionary valueForKey:srcString];

    if (results == nil)
    {
        return srcString;
    }// end if


    return results;
}



#pragma mark -
#pragma mark Singleton methods

static MyLanguage *mySharedSingleton = nil;

-(void) lateInit;
{

}

// PUT THIS METHOD DECLARATION INTO THE HEADER
+ (MyLanguage *)singleton;
{
    if (mySharedSingleton == nil) {
        mySharedSingleton = [[super allocWithZone:NULL] init];
        [mySharedSingleton lateInit];
    }
    return mySharedSingleton;
}

+ (id)allocWithZone:(NSZone *)zone
{    return [[self singleton] retain]; }

- (id)copyWithZone:(NSZone *)zone
{    return self; }

- (id)retain
{    return self; }

- (NSUInteger)retainCount //denotes an object that cannot be released
{    return NSUIntegerMax;  }

- (oneway void)release    //do nothing
{   }

- (id)autorelease
{     return self; }


@end

【讨论】:

  • 只是一些注释(可能不明显),以防有人想重用我的代码:语言环境 PLIST 文件是语言短 ID,后跟 GUIStings.plist,如 esGUIStrings.plist 和plist 中的根对象是一个名为“languageDictionary”的字典。字典中的条目由要翻译为键的字符串(如“Unlock”和“Log in”)组成,值是翻译后的字符串(如“Desbloquear”和“Iniciar la sesion”)。跨度>
  • Valet 是我创建的一个辅助类,它充当比 NSFileManager 更高级别的文件系统接口。我试图在发布代码之前删除对它的所有引用,但看起来我错过了一个。您可以在后面的代码中看到不使用 Valet 的类似行: NSString *path= [[NSBundle mainBundle] pathForResource:shortLanguageIdentifier ofType:@"lproj"];
【解决方案3】:

不要依赖您在 nib 文件中设置的字符串。仅将您的笔尖用于视图的布局和设置。向用户显示的任何字符串(按钮文本等)都需要在 Localizable.strings 文件中,并且当您加载 nib 时,您需要相应地在相应的视图/控件上设置文本。

获取当前语言的捆绑包:

NSString *path = [[NSBundle mainBundle] pathForResource:currentLanguage ofType:@"lproj"];
if (path) {
    NSBundle *localeBundle = [NSBundle bundleWithPath:path];
}

并使用捆绑包来获取您的本地化字符串:

NSLocalizedStringFromTableInBundle(stringThatNeedsToBeLocalized, nil, localeBundle, nil);

对于日期格式,您可能需要查看

[NSDateFormatter dateFormatFromTemplate:@"HH:mm:ss"" options:0 locale:locale];

要使用它,您需要为您希望使用的相应语言/国家/地区创建一个 NSLocale。

【讨论】:

  • 但是 xib 文件中的本地化图像呢?示例:按钮图像。对于不同的本地化,xib 文件中的不同布局和标签大小又如何呢?
  • 查看stackoverflow.com/questions/3787751/loading-a-localized-uiimage 获取有关加载图像的示例。
  • 您可能需要动态调整标签大小等。例如,您可能需要使用 -[NSString sizeWithFont: constrainedToSize: lineBreakMode:] 来确定某些文本所需的高度(或宽度)和然后相应地设置框架。
  • 话虽如此,使用与设备使用不同的语言/区域设置并不简单。即使您执行了上述所有操作,[NSError localedErrorDescription] 也会根据设备设置(或者可能根据 NSUserDefaults 的“AppleLanguages”)返回文本。但是根据我从其他问题和答案中看到的情况,您必须在启动 UIApplication 之前在您的 main 中设置它,因此您无法在应用程序运行时动态更改它,而无需重新启动您的应用程序。
【解决方案4】:

这就是我所做的。我想诀窍是使用 NSLocalizedStringFromTableInBundle 而不是 NSLocalizedString。

对于所有字符串,使用 this

someLabel.text = NSLocalizedStringFromTableInBundle(@"Your String to be localized, %@",nil,self.localeBundle,@"some context for translators");

要更改语言,请运行此代码

    NSString * language = @"zh-Hans"; //or whatever language you want
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
    if (path) {
        self.localeBundle = [NSBundle bundleWithPath:path];
    }
    else {
        self.localeBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"] ];
    }

在此之后,您可能需要调用任何更新代码来将字符串更新为新语言,例如再次运行它

someLabel.text = NSLocalizedStringFromTableInBundle(@"Your String to be localized, %@",nil,self.localeBundle,@"some context for translators");

仅此而已。无需重启应用程序。也与系统设置兼容(如果您通过 iOS 设置设置语言,它也可以工作)。不需要外部库。不需要越狱。它也适用于 genstrings。

当然,您仍应照常执行以使您的应用设置保持不变:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

(并检查您的 viewDidLoad 或其他内容)

NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
    if (path) {
        self.localeBundle = [NSBundle bundleWithPath:path];
    }
    else {
        self.localeBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"] ];
    }

【讨论】:

  • 这与我 2012 年的解决方案有何不同?
【解决方案5】:

您应该创建类似于 NSLocalizedString 的自己的宏,但它基于您设置的 NSUserDefaults 值来选择字符串(即不要担心苹果语言默认值的值)

当您更改语言时,您应该发送通知,哪些视图控制器、视图等应该监听并刷新自己

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    相关资源
    最近更新 更多