I am making ios app on XCODE 6.3 by Swift. And my app will have the choose language function like the image below
I already have storyboard for my local language. But i can't find out how to change the localization programmatically off the app by the button.
Anyone know how to do it
There is a language setting within the "Settings" app (a system app), and there the user can set the language. All installed apps will use this language setting.
The Locale object in Swift is used to retrieve some pieces of information on the Locale settings of the user. These settings can depend on the general set up of the device or on the settings for a specific app.
string file, select it and on the File Inspector (right menu) select “Localize”. Select your the new language you added and click on “Finish”. If you select the file again you should see something similar to the first image below (be sure to select both the supported languages).
Here's a way to change it on the fly with Swift, add an extension function to String:
extension String { func localized(lang:String) ->String { let path = NSBundle.mainBundle().pathForResource(lang, ofType: "lproj") let bundle = NSBundle(path: path!) return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "") }}
Swift 4:
extension String { func localized(_ lang:String) ->String { let path = Bundle.main.path(forResource: lang, ofType: "lproj") let bundle = Bundle(path: path!) return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "") }}
then assuming you have the regular Localizable.strings set up with lang_id.lproj ( e.g. en.lproj, de.lproj etc. ) you can use this anywhere you need:
var val = "MY_LOCALIZED_STRING".localized("de")
This allows to change the language just by updating a UserDefaults
key.
This is based on the great answer from @dijipiji. This is a Swift 3 version.
extension String { var localized: String { if let _ = UserDefaults.standard.string(forKey: "i18n_language") {} else { // we set a default, just in case UserDefaults.standard.set("fr", forKey: "i18n_language") UserDefaults.standard.synchronize() } let lang = UserDefaults.standard.string(forKey: "i18n_language") let path = Bundle.main.path(forResource: lang, ofType: "lproj") let bundle = Bundle(path: path!) return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "") } }
Usage
Just add .localized
to your string, as such :
"MyString".localized
, MyString
being a key in the Localizable.strings
file.
Changing the language
UserDefaults.standard.set("en", forKey: "i18n_language")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With