找到了此处描述的此问题的解决方案: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)
}
}