如何使用存储在CocoaTouch Framework中的Localizable.strings?

问题描述 投票:13回答:3

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

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

放置在CocoaTouch框架内时,如何使用Localizable.strings?

ios swift localization multilingual nslocalizedstring
3个回答
9
投票

使用:

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")

6
投票

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

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

0
投票

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

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是默认值。

© www.soinside.com 2019 - 2024. All rights reserved.