【问题标题】:Dynamic change of localization file in swiftswift中本地化文件的动态更改
【发布时间】:2021-10-29 11:04:41
【问题描述】:

我在我的应用程序中使用德语,并且有两种称呼“Du”和“Sie”的人。我想在我的项目中添加另一个可本地化的文件,其中将使用“Du”。基本上,我想知道是否有可能检查是否选择了德语和“Du”地址,如果可以,使用“Du”本地化文件?现在项目中只存在“Sie”文件,并从中获取本地化。

【问题讨论】:

  • 为什么不创建 .strings 文件并添加其他语言的本地化,并在 App delgate 中使用 getLanguage 函数获取设备的语言并根据该语言设置所需的语言
  • 当然!问题是如何做到这一点? Locale.currentLahguage 是 { get } 唯一属性。如果你能为此分享一个代码 sn-p 那就太好了。

标签: swift localization


【解决方案1】:

找到了此处描述的此问题的解决方案:Forcing iOS localization at runtime。但是,主要的一点是Bundle.swizzleLocalization() 应该在main.swift 文件中调用

if Locale.current.languageCode == "de" {
     let appConfig = ApplicationConfiguration()
     if appConfig.germanLanguageType == "du" {
         Bundle.swizzleLocalization()
     }
 }

因此,在 main.swift 文件中,我检查了设备的首选语言,如果是德语,我检查了我的 appConfig.swift 文件,其中指定了应用程序中是否应使用“du”或“sie”寻址是“du”我叫Bundle.swizzleLocalization()

在 Bundle 的扩展中,我只是调整了应该使用的本地化文件的路径(之前在项目中添加)

extension Bundle {

    static func swizzleLocalization() {
        let orginalSelector = #selector(localizedString(forKey:value:table:))
        guard let orginalMethod = class_getInstanceMethod(self, orginalSelector) else { return }
        
        let mySelector = #selector(myLocaLizedString(forKey:value:table:))
        guard let myMethod = class_getInstanceMethod(self, mySelector) else { return }
        
        if class_addMethod(self, orginalSelector, method_getImplementation(myMethod), method_getTypeEncoding(myMethod)) {
            class_replaceMethod(self, mySelector, method_getImplementation(orginalMethod), method_getTypeEncoding(orginalMethod))
        } else {
            method_exchangeImplementations(orginalMethod, myMethod)
        }
    }
    
    @objc func myLocaLizedString(forKey key: String,value: String?, table: String?) -> String {
        guard let bundlePath = Bundle.main.path(forResource: "de-DE", ofType: "lproj"),
              let bundle = Bundle(path: bundlePath) else {
                  return Bundle.main.myLocaLizedString(forKey: key, value: value, table: table)
              }
        return bundle.myLocaLizedString(forKey: key, value: value, table: table)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多