【问题标题】:"localizedStringWithFormat" change the language without restarting the app"localizedStringWithFormat" 更改语言而不重新启动应用程序
【发布时间】:2020-09-14 14:40:39
【问题描述】:

我在我的应用中成功实现了复数本地化。但如果我更改应用程序语言,localizedStringWithFormat 仍会返回以前语言的复数形式。

如果我重新启动应用程序,复数将以正确的语言(我选择的语言)返回。

是否有可能明确localizedStringWithFormat,它应该以哪种语言返回复数?

示例代码,其中调用了复数:

let candiesEaten: Int = 38
let candyCounterString: String = String.localizedStringWithFormat(NSLocalizedString("TEXT_CANDY_COUNTER", comment: ""), arguments: candiesEaten)

应用程序中的语言是这样更改的,它可以与所有其他字符串一起使用:

private static func setLanguageAndSynchronize(_ lang: [String]) {
        UserDefaults.standard.set(lang, forKey: Preferences.appleLanguagesKey)
        UserDefaults.standard.synchronize()
    }

【问题讨论】:

    标签: swift localization nslocalizedstring plural


    【解决方案1】:

    字符串扩展

    extension String {
      var localized: String {
        guard let path = Bundle.main.path(forResource: AppLanguageService.shared.getAppLanguage()?.rawValue, ofType: "lproj"),
              let bundle = Bundle(path: path) else { return "" }
        return bundle.localizedString(forKey: self, value: nil, table: nil)
      }
        
      func localizeWithFormat(arguments: CVarArg...) -> String {
         return String(format: self.localized, arguments: arguments)
      }
    }
    

    使用示例

    let formatedString = "TEXT_CANDY_COUNTER".localizeWithFormat(arguments: candiesEaten)
    

    How to use NSLocalizedString function with variables in Swift?

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2013-10-09
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      相关资源
      最近更新 更多