Search code examples
iosswiftbundlesettings

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!


Solution

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