我使用多语言应用程序,我想在配置文件用户中手动更改语言。
我已经有 Localization.string
如果我更改设备语言,应用程序中的语言将更改为。
但我想从用户配置文件示例中手动更改语言:
![enter image description here](https://i.stack.imgur.com/SmWjB.png)
为此,我使用下一个代码:
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()
}
@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) // see step #2
}
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)
}
我使用这个捆绑包:
Bundle.main.localizations.filter({ $0 != "Base" })
Locale.current.localizedString(forLanguageCode: "en")
对于这段代码我有:
![enter image description here](https://i.stack.imgur.com/t1lov.png)
当我按下按钮时,我收到错误:
原因:“添加到 UIAlertController 的操作必须有标题”
我不知道问题出在哪里。