我想为CocoaTouch框架添加多语言支持。
问题:我创建的Localizable.strings文件只有当它是主应用程序及其目标的一部分时才被NSLocalizedString使用。我想将它存储在Framework中以保持分离。
放置在CocoaTouch框架内时,如何使用Localizable.strings?
使用:
NSLocalizedString("Good", tableName: nil, bundle: NSBundle(forClass: self), value: "", comment: "")
或者您可以像这样创建公共函数:
class func POLocalized(key: String) -> String{
let s = NSLocalizedString(key, tableName: nil, bundle: NSBundle(forClass: self.classForCoder()), value: "", comment: "")
return s
}
使用示例:
let locString = POLocalized("key")
这可以通过在NSLocalizedString
构造函数中指定框架的包标识符来完成。
if let bundle: NSBundle = NSBundle(identifier: "com.mycompany.TheFramework") {
let string = NSLocalizedString("key", tableName: nil, bundle: bundle, value: "", comment: "")
print(string)
}
您可以将此结构添加到您的代码库:
internal struct InternalConstants {
private class EmptyClass {}
static let bundle = Bundle(for: InternalConstants.EmptyClass.self)
}
然后使用可选的bundle param指定字符串文件的位置:
let yourString = NSLocalizedString("Hello", bundle: InternalConstants.bundle, comment: "")
如果你不在Bundle.main
构造函数中使用bundle
param,则NSLocalizedString
是默认值。