Multiple Localized .strings Files in iOS App Bundle

前端 未结 5 1220
清酒与你
清酒与你 2020-12-09 13:07

I have a fairly complicated project, consisting of several large localized sub-projects.

Most of my sub-projects are localized through a single Localizable.s

5条回答
  •  一向
    一向 (楼主)
    2020-12-09 13:34

    I now have a hacky solution to this, but would appreciate if someone has a better answer (or explanation for why the above doesn't work).

    I expanded my NSBundle category to include a preferred language resource:

    Header

    @interface NSBundle (MyBundle)
    
    + (NSBundle*) myResourcesBundle;
    + (NSBundle*) myPreferredLanguageResourcesBundle;
    
    @end
    

    Implementation

    @implementation NSBundle (MyBundle)
    
    + (NSBundle*) myResourcesBundle
    {
        static dispatch_once_t onceToken;
        static NSBundle *myLibraryResourcesBundle = nil;
    
        dispatch_once(&onceToken, ^
        {
            myLibraryResourcesBundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"MyResources" withExtension:@"bundle"]];
        });
    
        return myLibraryResourcesBundle;
    }
    
    + (NSBundle*) myPreferredLanguageResourcesBundle
    {
        static dispatch_once_t onceToken;
        static NSBundle *myLanguageResourcesBundle = nil;
    
        dispatch_once(&onceToken, ^
                      {
                          NSString *language = [[[NSBundle myResourcesBundle] preferredLocalizations] firstObject];
                          myLanguageResourcesBundle = [NSBundle bundleWithPath:[[NSBundle myResourcesBundle] pathForResource:language ofType:@"lproj"]];
    
                          if( myLanguageResourcesBundle == nil )
                          {
                              myLanguageResourcesBundle = [NSBundle myResourcesBundle];
                          }                
                      });
    
        return myLanguageResourcesBundle;
    }
    
    @end
    

    I then have a simple macro for getting my localized strings:

    #define MyLocalizedDocumentation(key, comment, chapter) \
      NSLocalizedStringFromTableInBundle((key),(chapter),[NSBundle myPreferredLanguageResourcesBundle],(comment))
    

    This solution simply gets the preferred language code from NSLocale and then checks to see if a bundle exists for that language. If not, it falls back to the main resource bundle (perhaps it should iterate through the NSLocale preferredLanguage indices to check if a bundle exists? Does anyone know?)

提交回复
热议问题