how to change Application language on run time using Two Button in iphone SDK?

前端 未结 7 1339
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 06:30

i am building up a project in ios platform and want to use two language in this application and also want . the user can change the language on Runtime suppose we can ta

7条回答
  •  忘掉有多难
    2020-12-17 06:58

    I came up with a solution that allows you to use NSLocalizedString. I create a category of NSBundle call NSBundle+RunTimeLanguage. The interface is like this.

    // NSBundle+RunTimeLanguage.h
    #import 
    @interface NSBundle (RunTimeLanguage)
    #define NSLocalizedString(key, comment) [[NSBundle mainBundle] runTimeLocalizedStringForKey:(key) value:@"" table:nil]
    - (NSString *)runTimeLocalizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName;
    @end
    

    The implementation is like this.

    // NSBundle+RunTimeLanguage.m
    #import "NSBundle+RunTimeLanguage.h"
    #import "AppDelegate.h"
    
    @implementation NSBundle (RunTimeLanguage)
    
    - (NSString *)runTimeLocalizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
    {
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        NSString *path= [[NSBundle mainBundle] pathForResource:[appDelegate languageCode] ofType:@"lproj"];
        NSBundle *languageBundle = [NSBundle bundleWithPath:path];
        NSString *localizedString=[languageBundle localizedStringForKey:key value:key table:nil];
        return localizedString;
    }
    @end
    

    Than just add import NSBundle+RunTimeLanguage.h into the files that use NSLocalizedString.

    As you can see I store my languageCode in a property of AppDelegate. This could be stored anywhere you'd like.

    This only thing I don't like about it is a Warning that NSLocalizedString marco redefined. Perhaps someone could help me fix this part.

提交回复
热议问题