gpt4 book ai didi

iOS 如何重新启动应用程序以更改语言 Swift 4

转载 作者:行者123 更新时间:2023-11-28 11:48:03 26 4
gpt4 key购买 nike

我使用多语言应用程序,我想在配置文件用户中手动更改语言。

我已经有了 Localization.string

如果我更改设备语言,应用程序中的语言会更改为。

但我想从用户配置文件示例手动更改语言:

enter image description here

为此我使用下一个代码:

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

当我按下按钮时出现错误:

reason: 'Actions added to UIAlertController must have a title'

我不知道问题出在哪里。

最佳答案

在我最近的应用程序中,我使用了这个 localize ,它很简单,无需关闭应用程序,我们就可以根据语言切换应用程序。

将localize.swift文件添加到你的项目中,最后在你需要的地方调用下面的func

if let pre = Bundle.main.preferredLocalizations.first, !pre.isEmpty  {
if pre == Language.english.rawValue{
Language.language = Language.arabic
}else{
Language.language = Language.english
}

}

关于iOS 如何重新启动应用程序以更改语言 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52203442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com