直接在应用程序中切换语言
一直在尝试将我的应用程序本地化为7种语言,但是我发现的所有教程只显示如何在单个页面上显示,而不是显示在应用程序中。
我现在在设备是该语言的本地化工作的地步,但需要有能力通过button来改变语言。
编辑:下面的代码适用于任何人寻找类似的解决scheme。
有关以下注意事项
- 以下代码组创build一个应用程序语言更改,包括标签栏名称。
- 你必须把所有的数据放在localize.strings中,因为main.strings将不能正常工作。 这意味着你将需要以编程方式添加所有“后退”,“取消”和导航标题,以及菜单项。
- 每个“changeToXX”函数内的NSNotificationCenter都被设置为通知tabBarViewController(或任何需要的控制器)语言已经改变。
一世
import UIKit let AppLanguageKey = "AppLanguage" let AppLanguageDefaultValue = "" var appLanguage: String { get { if let language = NSUserDefaults.standardUserDefaults().stringForKey(AppLanguageKey) { return language } else { NSUserDefaults.standardUserDefaults().setValue(AppLanguageDefaultValue, forKey: AppLanguageKey) return AppLanguageDefaultValue } } set(value) { NSUserDefaults.standardUserDefaults().setValue((value), forKey: AppLanguageKey) } } let languageChangedKey = "languageChanged" class SettingsLanguageVC: UIViewController { @IBOutlet weak var languageENButton: UIButton! @IBOutlet weak var flagENImageView: UIImageView! @IBOutlet weak var languageENTitleLabel: UILabel! @IBOutlet weak var checkmarkEN: UIImageView! @IBOutlet weak var languageDEButton: UIButton! @IBOutlet weak var flagDEImageView: UIImageView! @IBOutlet weak var languageDETitleLabel: UILabel! @IBOutlet weak var checkmarkDE: UIImageView! @IBOutlet weak var languageFRButton: UIButton! @IBOutlet weak var flagFRImageView: UIImageView! @IBOutlet weak var languageFRTitleLabel: UILabel! @IBOutlet weak var checkmarkFR: UIImageView! @IBOutlet weak var languageESButton: UIButton! @IBOutlet weak var flagESImageView: UIImageView! @IBOutlet weak var languageESTitleLabel: UILabel! @IBOutlet weak var checkmarkES: UIImageView! var tabBar = TabBarController() var MyDelegateClass = "" override func viewDidLoad() { super.viewDidLoad() configureView() print(appLanguage) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back".localized, style: .Plain, target: self, action: #selector(SettingsLanguageVC.back(_:))) navigationItem.title = "Select a language".localized } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setTranslatedText(){ if appLanguage == "es" { checkmarkShowES() } else if appLanguage == "de" { checkmarkShowDE() } else if appLanguage == "fr" { checkmarkShowFR() } else { checkmarkShowEN() } } func configureView(){ let localeEN = NSLocale(localeIdentifier: "en") let English = localeEN.displayNameForKey(NSLocaleIdentifier, value: "en") languageENTitleLabel.text = English flagENImageView.image = UIImage(named: "flag-en.png") languageENButton.addTarget(self, action: #selector(self.changeToEN), forControlEvents: .TouchUpInside) //German let localeDE = NSLocale(localeIdentifier: "de") let German = localeDE.displayNameForKey(NSLocaleIdentifier, value: "de") languageDETitleLabel.text = German flagDEImageView.image = UIImage(named: "flag-de.png") languageDEButton.addTarget(self, action: #selector(self.changeToDE), forControlEvents: .TouchUpInside) //French let localeFR = NSLocale(localeIdentifier: "fr") let French = localeFR.displayNameForKey(NSLocaleIdentifier, value: "fr") languageFRTitleLabel.text = French flagFRImageView.image = UIImage(named: "flag-fr.png") languageFRButton.addTarget(self, action: #selector(self.changeToFR), forControlEvents: .TouchUpInside) //Spanish let localeES = NSLocale(localeIdentifier: "es") let Spanish = localeES.displayNameForKey(NSLocaleIdentifier, value: "es") languageESTitleLabel.text = Spanish flagESImageView.image = UIImage(named: "flag-es.png") languageESButton.addTarget(self, action: #selector(self.changeToES), forControlEvents: .TouchUpInside) if appLanguage == "es" { checkmarkShowES() } else if appLanguage == "de" { checkmarkShowDE() } else if appLanguage == "fr" { checkmarkShowFR() } else { checkmarkShowEN() } } func changeToEN(sender: UIButton) { checkmarkShowEN() appLanguage = "en" NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self) [self.viewDidLoad()] } func changeToDE(sender: UIButton) { appLanguage = "de" NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self) [self.viewDidLoad()] } func changeToFR(sender: UIButton) { checkmarkShowFR() appLanguage = "fr" NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self) [self.viewDidLoad()] } func changeToES(sender: UIButton) { checkmarkShowES() appLanguage = "es" NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(languageChangedKey, object: self) [self.viewDidLoad()] } func checkmarkShowEN (){ self.checkmarkEN.hidden = false self.checkmarkDE.hidden = true self.checkmarkFR.hidden = true self.checkmarkES.hidden = true } func checkmarkShowDE (){ self.checkmarkEN.hidden = true self.checkmarkDE.hidden = false self.checkmarkFR.hidden = true self.checkmarkES.hidden = true } func checkmarkShowFR (){ self.checkmarkEN.hidden = true self.checkmarkDE.hidden = true self.checkmarkFR.hidden = false self.checkmarkES.hidden = true } func checkmarkShowES () { self.checkmarkEN.hidden = true self.checkmarkDE.hidden = true self.checkmarkFR.hidden = true self.checkmarkES.hidden = false } @IBAction func back (sender: AnyObject) { //back one VC navigationController?.popViewControllerAnimated(true) } }
所有需要本地化的文本,都需要有.local的后缀,以及下面的StringExtension.swift
extension String { var localized: String { return localized(appLanguage) } var localizeStringUsingSystemLang: String { return NSLocalizedString(self, comment: "") } func localized(lang:String?) -> String { if let lang = lang { if let path = NSBundle.mainBundle().pathForResource(lang, ofType: "lproj") { let bundle = NSBundle(path: path) return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "") } } return localizeStringUsingSystemLang } } return localizeStringUsingSystemLang } }
这是TabBarController代码:
-
注意:标签“search”,“collections夹”和“更多”是系统选项卡。 我不得不将它们更改为自定义,并手动将名称添加到选项卡并添加我自己的图标。 否则,他们不会被本地化。
导入UIKit
类TabBarController:UITabBarController {
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setTabViewControllerParams(0, tabBarItemTitle: "Species".localized, navigationItemTitle: filterBy) setTabViewControllerParams(1, tabBarItemTitle: "Regions".localized, navigationItemTitle: "My Regions".localized) setTabViewControllerParams(2, tabBarItemTitle: "Favorites".localized, navigationItemTitle: "Favorites".localized) setTabViewControllerParams(3, tabBarItemTitle: "Search".localized, navigationItemTitle: "") setTabViewControllerParams(4, tabBarItemTitle: "More".localized, navigationItemTitle: "Reef Life Apps") NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TabBarController.languageChangedTrigger), name: languageChangedKey, object: nil) } func languageChangedTrigger () { [self.viewDidLoad()] } func setTabViewControllerParams(index: Int, tabBarItemTitle: String, navigationItemTitle: String) { if let tabBarItems = tabBar.items { if index < tabBarItems.count { tabBarItems[index].title = tabBarItemTitle } } if let viewControllers = viewControllers { if index < viewControllers.count { if let navigationController = viewControllers[index] as? UINavigationController { if navigationController.viewControllers.count > 0 { let viewController = navigationController.viewControllers[0] viewController.navigationItem.title = navigationItemTitle } } } } }
}
最后,我将下面的内容添加到了AppDelegate的“didFinishLaunchingWithOptions”中,以便在非英语的手机启动时,应用程序将以其语言启动,而不是默认的英语。
if NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String == "es" { appLanguage = "es" }else if NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String == "fr" { appLanguage = "fr" }else if NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String == "de" { appLanguage = "de" }else { appLanguage = "en" }
希望这可以帮助。
试试这个例子:
ViewController.swift
import UIKit let AppLanguageKey = "AppLanguage" let AppLanguageDefaultValue = "en" var appLanguage: String { get { if let language = NSUserDefaults.standardUserDefaults().stringForKey(AppLanguageKey) { return language } else { NSUserDefaults.standardUserDefaults().setValue(AppLanguageDefaultValue, forKey: AppLanguageKey) return AppLanguageDefaultValue } } set(value) { NSUserDefaults.standardUserDefaults().setValue((value), forKey: AppLanguageKey) } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NSLog("title user lang: \("Title".localizeString)") NSLog("title En: \("Title".localizeString("en"))") NSLog("title Ru: \("Title".localizeString("ru"))") NSLog("title Fr: \("Title".localizeString("fr"))") NSLog("title ??: \("Title".localizeString("blabla"))") NSLog("title sysem lnag: \("Title".localizeStringUsingSystemLang)") // Do any additional setup after loading the view, typically from a nib. } }
StringExtension.swift
import Foundation extension String { var localizeString: String { return localizeString(appLanguage) } var localizeStringUsingSystemLang: String { return NSLocalizedString(self, comment: "") } func localizeString(lang:String?) -> String { if let lang = lang { if let path = NSBundle.mainBundle().pathForResource(lang, ofType: "lproj") { let bundle = NSBundle(path: path) return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "") } } return localizeStringUsingSystemLang } }
Localizable.strings(俄语)
"Title" = "Привет";
Localizable.strings(英文)
"Title" = "Hello";
Localizable.strings(法语)
"Title" = "Salut";
结果: