如何以编程方式获取显示在 iOS 设置应用程序中的本地化字符串?

How to programmatically get the localized string as it displayed in iOS Settings App?

我用Settings.bundle。有一个关于“颜色”的项目。这是一段文件 Root.plist:

        <dict>
            <key>Type</key>
            <string>PSMultiValueSpecifier</string>
            <key>Key</key>
            <string>Color</string>
            <key>Title</key>
            <string>Color </string>
            <key>DefaultValue</key>
            <integer>1</integer>
            <key>Titles</key>
            <array>
                <string>Blue</string>
                <string>Green</string>
                <string>Red</string>
            </array>
            <key>Values</key>
            <array>
                <integer>0</integer>
                <integer>1</integer>
                <integer>2</integer>
            </array>
        </dict>

然后我将其本地化,例如通过文件 es.lproj/Root.strings:

进行西班牙语本地化
"Blue" = "Azul";
"Green" = "Verde ";
"Red" = "Rojo";

它们在“设置”应用上运行良好。


现在我需要以编程方式获取显示在 iOS 设置应用程序中的本地化颜色名称。

例如:我通过

得到了值1
let r = UserDefaults.standard.value(forKey: "Color") as? Int

如何从值 1 或“Green”中获取字符串“Verde”?

关键是:我不想复制 es.lproj/Localizable.strings 中的翻译,func NSLocalizedString().

非常感谢任何帮助!

从 Table 阅读它,如下所示:

if let path = Bundle.main.path(forResource: "Settings", ofType: "bundle") {
     let settingBundle = Bundle.init(path: path)
     print(settingBundle)
     let lString = NSLocalizedString("Color Name", tableName: "Root", bundle: settingBundle!, value: "Not found", comment: "")
     print(lString)
}

我这样做:

        if let serverStringsUrl = Bundle.main.url(forResource: "Root", withExtension: "strings", subdirectory: "Settings.bundle/en.lproj"),
        let serverStringsDict = NSDictionary(contentsOf: serverStringsUrl) as? [String: String] {
            // Use your key to access your localized color value from serverStringsDict here. 
            print(serverStringsDict)
    }

加载文件时,需要指定本地化文件。即本地化的“Settings.bundle/xxx.lproj”.