iOS本地化:dynamic本地化视图,而不会搞乱storyboard / nibstring文件

所以我有这个问题,我想本地化我的应用程序中的所有视图。 我已经提供了Localizablestring文件,包括所有的翻译。 但是,当我尝试使用string文件本地化故事板时,它显示为如下代码:

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

而且我已经有了一些文本翻译来本地化的string文件本地化。 但手动交叉引用他们的所有语言似乎是一个痛苦。 特别是当故事板改变,我不得不重新出口他们,并添加新的。

我已经有一个class级语言pipe理器 ,为我本地化string。 这是一个非常简单的类,其中最重要的方法就是这个

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

我通过编写一个方法来循环遍历视图控制器中的所有视图,并将它们本地化。 我决定分享这个,因为我认为它非常有用,可以在任何视图控制器中以即插即用的方式工作,并避免导出Storyboardystring文件的循环,添加到它们中,并在发生更改时重新集成它们。 这样你就可以添加到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) } }