简体   繁体   中英

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

I use Settings.bundle. There is an item about "Color". Here is a piece of file 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>

And I localize it, for example, Spannish by file es.lproj/Root.strings :

"Blue" = "Azul";
"Green" = "Verde ";
"Red" = "Rojo";

They work fine on Settings App.


Now I need to programmatically get the localized color name as it displayed in iOS Settings App.

For example: I've got the value of 1 by

let r = UserDefaults.standard.value(forKey: "Color") as? Int

How can I get the String of "Verde" out of the value 1 or "Green"?

The key is: I don't want to duplicate the translations in es.lproj/Localizable.strings which is used by func NSLocalizedString().

Any help is greatly appreciated!

Read It from Table like following:

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)
}

I do this:

        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)
    }

When you load the file, you will need to specify the localized file. That is, the localized "Settings.bundle/xxx.lproj".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM