Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to add multi-language support to a CocoaTouch Framework.

The problem: The Localizable.strings file I created only gets used by NSLocalizedString when it's part of the main app and its target. I'd like to store it inside the Framework to keep things separate.

How can I use the Localizable.strings when placed inside a CocoaTouch Framework?

like image 839
Bernd Avatar asked Feb 25 '15 16:02

Bernd


People also ask

How do I add localizable strings?

To add Localizable. strings file, go to File->New->File , choose Strings File under Resource tab of iOS, name it Localizable. strings , and create the file. Now, you have a Localizable.

What are localization strings?

A localized string can have different values depending on the language in which the project is being build. There are two categories of localized strings: the strings included in the installation package's UI, common to every MSI file.


3 Answers

Use:

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

or you can create public func like this:

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

example of use:

let locString = POLocalized("key")
like image 89
pbeo Avatar answered Oct 16 '22 08:10

pbeo


This can be done by specifying the bundle identifier of the framework in the NSLocalizedString constructor.

if let bundle: NSBundle = NSBundle(identifier: "com.mycompany.TheFramework") {
    let string = NSLocalizedString("key", tableName: nil, bundle: bundle, value: "", comment: "")
    print(string)
}
like image 30
Kyle Clegg Avatar answered Oct 16 '22 09:10

Kyle Clegg


You can add this struct to your codebase:

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

And then use optional bundle param to specify the location of your string file:

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

Bundle.main is the default value if you don't use bundle param in your NSLocalizedString constructor.

like image 29
Kirill Kudaev Avatar answered Oct 16 '22 09:10

Kirill Kudaev