以下是如何使用Novarg方法的简单易懂的现成的、逐步指南,适用于Swift 3:
第一步:实现语言选择器
如何最好地实现这一点取决于项目,但请使用:
Bundle.main.localizations.filter({ $0 != "Base" }) // => ["en", "de", "tr"]
以编程方式获取您所有支持的语言环境语言代码的列表。此外,您可以使用
Locale.current.localizedString(forLanguageCode: "en") // replace "en" with your variable
在应用中展示语言名称,并使用当前语言。
例如,在单击按钮后,您可以像这样展示一个弹出操作表:
@IBOutlet var changeLanguageButton: UIButton!
@IBAction func didPressChangeLanguageButton() {
let message = "Change language of this app including its content."
let sheetCtrl = UIAlertController(title: "Choose language", message: message, preferredStyle: .actionSheet)
for languageCode in Bundle.main.localizations.filter({ $0 != "Base" }) {
let langName = Locale.current.localizedString(forLanguageCode: languageCode)
let action = UIAlertAction(title: langName, style: .default) { _ in
self.changeToLanguage(languageCode)
}
sheetCtrl.addAction(action)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
sheetCtrl.addAction(cancelAction)
sheetCtrl.popoverPresentationController?.sourceView = self.view
sheetCtrl.popoverPresentationController?.sourceRect = self.changeLanguageButton.frame
present(sheetCtrl, animated: true, completion: nil)
}
步骤#2:告诉用户该做什么+重启后更改语言
您可能已经注意到,在步骤#1中的代码调用了一个名为changeToLanguage(langCode:)
的方法。无论您如何设计选择器,当用户选择要切换到的新语言时,这就是您应该执行的操作。这是它的实现,只需将其复制到您的项目中:
private func changeToLanguage(_ langCode: String) {
if Bundle.main.preferredLocalizations.first != langCode {
let message = "In order to change the language, the App must be closed and reopened by you."
let confirmAlertCtrl = UIAlertController(title: "App restart required", message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Close now", style: .destructive) { _ in
UserDefaults.standard.set([langCode], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
exit(EXIT_SUCCESS)
}
confirmAlertCtrl.addAction(confirmAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
confirmAlertCtrl.addAction(cancelAction)
present(confirmAlertCtrl, animated: true, completion: nil)
}
}
这将询问并通知用户是否希望进行更改以及如何进行更改。此外,它会在下一次启动时设置应用程序的语言:
UserDefaults.standard.set([langCode], forKey: "AppleLanguages")
UserDefaults.standard.synchronize() // required on real device
第三步(可选):本地化字符串
您可以使用NSLocalizedString
宏(或任何其他增强的方法)来本地化诸如“立即关闭”之类的字符串。
现实世界的例子
我在一个针对iOS 10的应用程序中使用了这个确切的实现,我可以确认它在模拟器和设备上都可以正常工作。该应用程序实际上是开源的,因此您可以在这里找到以上代码分布在不同的类中。