关于ios:如何使用Cocoa Touch Framework中存储的Localizable.strings?

How to use Localizable.strings stored in a CocoaTouch Framework?

我想为CocoaTouch框架添加多语言支持。

问题:当我创建的Localizable.strings文件是主应用程序及其目标的一部分时,它才被NSLocalizedString使用。我想将其存储在Framework中,以使各部分分开。

当放置在CocoaTouch Framework中时,如何使用Localizable.strings?


使用:

1
NSLocalizedString("Good", tableName: nil, bundle: NSBundle(forClass: self), value:"", comment:"")

或者您可以像这样创建公共功能:

1
2
3
4
class func POLocalized(key: String) -> String{
        let s =  NSLocalizedString(key, tableName: nil, bundle: NSBundle(forClass: self.classForCoder()), value:"", comment:"")
        return s
    }

使用示例:

1
let locString = POLocalized("key")


这可以通过在NSLocalizedString构造函数中指定框架的包标识符来完成。

1
2
3
4
if let bundle: NSBundle = NSBundle(identifier:"com.mycompany.TheFramework") {
    let string = NSLocalizedString("key", tableName: nil, bundle: bundle, value:"", comment:"")
    print(string)
}

您可以将此结构添加到您的代码库中:

1
2
3
4
internal struct InternalConstants {
    private class EmptyClass {}
    static let bundle = Bundle(for: InternalConstants.EmptyClass.self)
}

然后使用可选的bundle参数来指定您的字符串文件的位置:

1
let yourString = NSLocalizedString("Hello", bundle: InternalConstants.bundle, comment:"")

如果不在NSLocalizedString构造函数中使用bundle参数,则

Bundle.main是默认值。