本地化
在我的应用程序中运行良好。我想要本地化权限对话框短信。它可以很好地适应设备语言的更改,但我想根据我的应用程序语言更改消息。
我尝试过以下代码
import UIKit
class LocalizeHelper: NSObject {
private var myBundle: Bundle? = nil
static let shared: LocalizeHelper = {
let instance = LocalizeHelper()
return instance
}()
override init() {
super.init()
// use systems main bundle as default bundle
myBundle = Bundle.main
}
func localizedString(forKey key: String) -> String {
return myBundle!.localizedString(forKey: key, value: "", table: nil)
}
// Converted with Swiftify v1.0.6331 - https://objectivec2swift.com/
func setLanguage(_ lang: String) {
// path to this languages bundle
let path: String? = Bundle.main.path(forResource: lang, ofType: "lproj")
if path == nil {
// there is no bundle for that language
// use main bundle instead
myBundle = Bundle.main
}
else {
// use this bundle as my bundle from now on:
myBundle = Bundle(path: path!)
// to be absolutely shure (this is probably unnecessary):
if myBundle == nil {
myBundle = Bundle.main
}
}
}
func getLanguage() -> String {
print("\(String(describing: myBundle?.bundlePath.last))")
//return myBundle!.bundlePath.last >> Error
return myBundle!.bundlePath.lastCharacter!
}
}
extension String {
public var lastCharacter: String? {
guard let aLast = self.last else {
return nil
}
return String(aLast)
}
}
我在 StackOverflow 上冲浪,但没有找到任何解决方案。我们感谢任何帮助外壳。
最佳答案
您最好的选择是将应用程序的语言保存在用户默认值中,例如作为字符串,然后当您将其从用户默认值中取出时,将其解析为自定义应用程序语言枚举。如果您没有保存任何应用程序语言,您始终可以使用设备语言,但更喜欢或使用用户默认值不为零的应用程序语言覆盖它。另外,最好您应该将用户默认交互与您在 View Controller 中访问的用户默认管理器进行包装。
因此建议的步骤是:
- 创建用户默认管理器
- 定义语言枚举
- 实现setLanguage函数语言参数
- 使用设备语言实现 getLanguage func 语言输出或 英语作为守卫返回
关于ios - 基于应用程序语言而不是设备语言的本地化请求权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57096679/