在iPhone上NSLocalizedString返回iPhone语言的字符串。 是否有可能强制NSLocalizedString使用特定语言来拥有应用程序 用不同的语言吗?


当前回答

你觉得Swift 3的这个解决方案怎么样?

extension String {

    func localized(forLanguage language: String = Locale.preferredLanguages.first!.components(separatedBy: "-").first!) -> String {

        guard let path = Bundle.main.path(forResource: language == "en" ? "Base" : language, ofType: "lproj") else {

            let basePath = Bundle.main.path(forResource: "Base", ofType: "lproj")!

            return Bundle(path: basePath)!.localizedString(forKey: self, value: "", table: nil)
        }

        return Bundle(path: path)!.localizedString(forKey: self, value: "", table: nil)
    }
}

简单的用法:

"report".localized(forLanguage: "pl") //forced language
"report".localized() //default language selected by user in settings, in case when your app doesnt support selected lanaguage, the default one is selected, here is an english.

其他回答

你可以用你想要做这件事的本地化字符串集构建一个子bundle,然后使用NSLocalizedStringFromTableInBundle()来加载它们。(我假设这是与你可能在应用上做的正常UI本地化分开的内容。)

你可以这样做:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings" inDirectory:nil forLocalization:@"es"];


NSBundle *spanishBundle = [[NSBundle alloc] initWithPath:[bundlePath stringByDeletingLastPathComponent]];

NSLocalizedStringFromTableInBundle(@"House", nil, spanishBundle, nil):

也许你应该补充这个(在.pch文件#import后):

extern NSBundle* bundle; // Declared on Language.m

#ifdef NSLocalizedString
    #undef NSLocalizedString
    // Delete this line to avoid warning
    #warning "Undefining NSLocalizedString"
#endif

#define NSLocalizedString(key, comment) \
    [bundle localizedStringForKey:(key) value:@"" table:nil]

在.pch文件中定义:

#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]


#define NSLocalizedString(str,nil) NSLocalizedStringFromTableInBundle(str, nil, currentLanguageBundle, @"")

无论你做什么,最好的方法是获取指定语言的short_name,即:fr, en, nl, de, it,等等…并将其赋值为全局值。

使选择器视图像下拉菜单一样弹出(单击一个按钮,选择器视图从下面出现一个语言列表),并选择您想要的语言。让短名称存储在内部。 创建一个名为LocalisedString的.h + .m文件。

将short_name的全局值设置为LocalisedString.m中获取的值 当选择所需的语言时,分配NSBundlePath为所需的语言创建项目子目录。例如,nl。项目,en.proj。

当选择特定的proj文件夹时,调用相应语言的本地化字符串并动态更改语言。

没有违反规则。