Localization iOS. Locate views dynamically without loading storyboard / nib line files.

So, I had this problem, I wanted to localize all the views in my application. I was provided with localizable string files, including all translations. However, when I tried to localize the storyboard using line files, it would look like code:

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

And I already have a translation in Some Text for localization in localized string files. But manual cross-reference to them for all languages ​​seemed a pain. Especially when the storyboard changes, and I have to re-export them and add new ones.

0
source share
1 answer

, . ,

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

, , . , , , , Storyboardy, , . Localizable.strings .

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

Source: https://habr.com/ru/post/1670762/


All Articles