我已经有一个班语言管理器,为我本地化字符串。这是一个非常简单的类,它最重要的方法是这样的
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)
}
}