I already have a class Language Manager that localises strings for me. It is a very simple class which most important method is this
func localizeString(stringToLocalize:String) -> String
{
// Get the corresponding bundle path.
let selectedLanguage = self.getLanguage()
let path = Bundle.main.path(forResource: selectedLanguage, ofType: "lproj")
// Get the corresponding localized string.
let languageBundle = Bundle(path: path!)
return languageBundle!.localizedString(forKey: stringToLocalize, value: "", table: nil)
}
I expanded upon this by writing a method to loop recursively through all views in a view controller, localizing them as it goes. I decided to share this because I think it is quite useful, will work as plug and play in any view controller, and will avoid the cycle of exporting Storyboardy strings files, adding to them, and reintegrating them whenever there is a change. This way you just add to the Localizable.strings file(s) and everything is automatically handled for you.
func localizeUI(parentView:UIView)
{
for view:UIView in parentView.subviews
{
if let potentialButton = view as? UIButton
{
if let titleString = potentialButton.titleLabel?.text {
potentialButton.setTitle(localizeString(stringToLocalize: titleString), for: .normal)
}
}
else if let potentialLabel = view as? UILabel
{
if potentialLabel.text != nil {
potentialLabel.text = localizeString(stringToLocalize: potentialLabel.text!)
}
}
localizeUI(parentView: view)
}
}