0
votes

So I had this problem, I wanted to localize all views in my app. I have been provided with Localizable strings files including all translations. However, when I tried to localize the storyboard using strings files, it shows as code like this:

/* Class = "UILabel"; text = "Name:"; ObjectID = "21M-2X-4Pf"; */
"21M-2X-4Pf.text" = "Some text to localize";

And I already have the translation to Some Text to localize in the localizable strings files. But manually cross-referencing them for all languages seemed like a pain. Especially when the storyboard changes and I have to re-export them and add the new ones.

1

1 Answers

1
votes

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