我用 Swift 创建了一个框架并为其提供了本地化。但是,我希望框架的用户能够在运行时覆盖本地化字符串。这是我到目前为止所做的:
1. Inside the framework, I created a LocalizationBundle variable and set its default value to the framework’s own bundle identifier.
2. When the framework is initialized, if this value is overridden (i.e., set to the main app’s bundle), the localization is fetched from there and it works fine.
这是我实现的代码:
public class SDK {
private var localizationBundle: Bundle!
public func configure(bundle: Bundle = .init(identifier: "com.test.SDK")!) {
self.bundle = bundle
}
public func getBundle() -> Bundle {
return localizationBundle
}
}
extension String {
func localized(in bundle: Bundle = SDK.shared.getBundle(), withComment comment: String? = nil) -> String {
return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: comment ?? "")
}
}
这似乎有效,但我不完全确定这是否是最好或最常见的方法。我有几个问题:
预先感谢您的见解!
对于您的框架本地化覆盖,这是简单的解决方案:
public class LocalizationManager {
static var bundle: Bundle = Bundle(for: LocalizationManager.self)
public static func setCustomBundle(_ newBundle: Bundle) {
bundle = newBundle
}
public static func localizedString(for key: String) -> String {
return NSLocalizedString(key, bundle: bundle, comment: "")
}
}
然后像这样使用它:
// In framework
let text = LocalizationManager.localizedString(for: "hello_world")
// In app
LocalizationManager.setCustomBundle(Bundle.main)
这可以处理 .strings 文件和字符串目录,并使事情变得简单且可维护。