NSLocalizedString not defaulting to Base language

后端 未结 4 2129
情话喂你
情话喂你 2021-02-20 09:20

I have the following problem with a small iOS 7 project on which I\'m testing the localisation capabilities.

  • I have a default project, with one VC, in which I have
4条回答
  •  后悔当初
    2021-02-20 09:53

    I have created the following class, which supports a fallback to a customizable language. In my case I use Base.lproj as file for my default language contents.

    StringUtilities.h

    @interface StringUtils : NSObject
    
    #define GetLocalizedString(key) [StringUtils getLocalizedString:key comment:nil]
    //#define GetLocalizedString(key,comment) [StringUtils getLocalizedString:key comment:comment]
    
    
    + (NSString*) getLocalizedString:(NSString*)key comment:(NSString*)comment;
    
    @end
    

    StringUtilities.m

    #import "StringUtilities.h"
    
    @implementation StringUtils
    
    
    //Returns a localized string, with fallback to version of Base
    + (NSString*) getLocalizedString:(NSString*)key comment:(NSString*)comment {
        NSString* localizedString = NSLocalizedString(key, nil);
    
        //use base language if current language setting on device does not find a proper value
        if([localizedString isEqualToString:key]) {
    
            NSString * path = [[NSBundle mainBundle] pathForResource:@"Base" ofType:@"lproj"];
            NSBundle * bundle = nil;
            if(path == nil){
                bundle = [NSBundle mainBundle];
            }else{
                bundle = [NSBundle bundleWithPath:path];
            }
            localizedString = [bundle localizedStringForKey:key value:comment table:nil];
        }
        return localizedString;
    }
    
    @end
    

    How to use

    Import the header file and use the GetLocalizedString macro instead of NSLocalizedString macro.

    #import "StringUtilities.h"
    
    NSString* str = GetLocalizedString(@"your.text.key");
    

提交回复
热议问题