MHLocalizationKit
MHLocalizationKit is an utility and infrastructure library that can be used for runtime language changes by modifying the behavior of the standard iOS localization system and using the same translation resources.
In short - you continue to use .strings files and NSLocalizedString macros/functions with the ability to specify and change the language at runtime.
How it works
The standard NSLocalizedString macros/functions are actually using the Bundle.localizedString(forKey:value:table:). Internally this method loads the needed .strings files based on the system's language.
What this library does is, by using method swizzling, to alter the default behaviour of Bundle to force it to load .strings from a bundle pointing directly to the directory of the .strings files for the applied language at runtime.
Installation
Carthage
Add github "KoCMoHaBTa/MHLocalizationKit" to your Cartfile, then Embed the framework directly into your project.
Cocoapods
Add pod 'MHLocalizationKit' to your Podfile
Submodules
Add a submodule to your repostiroy, then Embed the framework directly into your project
Manually
Download, then Embed the framework directly into your project
How to use
Basics
- in you
UIViewControllersubclasses that you wish to handle runtime language changes - conform to theLocalizableprotocol - implement
languageDidChange(from:to:)and load your localized string from there using the standardNSLocalizedStringmacros/functions. - when your app launches - set the desired value to
Bundle.language- this will calllanguageDidChange(from:to:)on all alive view controllers that conform to theLocalizableprotocol.
NSLocalizedString functions
As of Xcode 11, genstrings now works with the swift version of NSLocalizedString, so the overload functions has been removed due to their incompatibility with the updated genstrings.
Details
The language setting is persisted between application launches.
UIViewController subclasses that conforms to Localizable protocol will receive languageDidChange(from:to) call automatically upon viewDidLoad(). This is achieved using method swizzling.
You could opt-in for automatic system language and locale tracking by setting to true respectively Bundle.trackSystemLanguageChanges and Bundle.trackSystemLocaleChanges
You could subscribe for language change notifications by using LanguageWillChangeNotificationName and LanguageDidChangeNotificationName
Changelog
1.0.0
- initial documented version