我正在创建一个应用程序,现在我想提供英语和德语。我检查了项目配置中的Base本地化标记,并添加了German
。我把英语作为开发语言。
然后我创建了一个文件Translation.plist
,它基本上由我称之为类别的字典组成,例如我有一个字典用于按钮文本,标签文本等。每个类别字典再次由包含两个字符串的字典组成:值和注释。 Translation.plist通过XCode
进行了本地化。文件夹Base.lproj
,en.lproj
和de.lproj
存在,并按预期包含plist文件的副本。
然后我创建了一个类Translator.swift
,它应该将Translation.plist
文件作为NSDictionary
加载,具体取决于用户的首选语言环境。代码如下所示:
func relevantDictionary(category: String) -> NSDictionary {
let preferredLocale = Bundle.main.preferredLocalizations.first ?? "Base"
NSLog("User's preferred locale is \(preferredLocale)")
guard let url = Bundle.main.url(forResource: "Translation", withExtension: "plist") else {
fatalError("Could not find Translation.plist")
}
NSLog("Using \(url.absoluteURL) for translation")
guard let root = NSDictionary(contentsOf: url) else {
fatalError("Could not find dictionary for category (locale=\(preferredLocale)")
}
guard let relevant = root.value(forKey: category) as? NSDictionary else {
fatalError("Could not create dictionary from Translation.plist")
}
return relevant
}
然后我创建了一个使用Translator的String扩展,如下所示:
func localize(category: String) -> String {
return Translator.instance.translate(category: category, string: self)
}
有了这个,我通过“是”.localize(“按钮”)调用翻译器。在英语中,我希望“是”,用德语我会期待“Ja”。日志说明如下:
2017-07-05 08:45:24.728 myApp [13598:35048360]用户首选的语言环境是de_DE
2017-07-05 08:45:24.728 myApp [13598:35048360]使用file:/// Users / me / Library / Developer / CoreSimulator / Devices / A39D3318-943D-4EFE-BB97-5C2218279132 / data / Containers /Bundle/Application/4614E696-B52E-4C30-BBE8-3C76F6392413/myApp.app/Base.lproj/Translation.plist for translation
我想知道为什么会发生这种情况以及我错过了什么。我原本期望加载de.lproj/Translation.plist
而不是Base.lproj/Translation.plist
。
非常感谢任何帮助。
答案 0 :(得分:0)
您可以使用单个.plist文件执行此操作。您不需要为它创建不同的.plist文件。
Firstly, Add English and German countries with locale in Project -> info
https://i.stack.imgur.com/M4QIY.png
Once, you added countries with locale in Project -> info then add localizable.strings file in your bundle.
https://i.stack.imgur.com/lnjgL.png
At the end, just add country's locale in your language support class.
NSArray* languages = @[@"en", @"de"];`enter code here`
NSString *current = [languages objectAtIndex:0];
[self setLanguage:current];
希望它会对你有所帮助。