In one of my projects I need localised images. I like to use Asset Catalogs. I did expect that it would be possible to create and use localised versions of Asset Catalogs:
- MyImages.xcassets-en
- MyImages.xcassets-nl
This way I can simply create one Asset Catalog for each language that my app supports. I let the iOS localisation infrastructure pick the Asset Catalog for the language that best matches the preferred language of the user. The image is taken from this Asset Catalog.
To me this would seem to be a nice feature, but probably there is a good reason that it is not supported (yet).
So I need something else, and I found a solution that seems pretty elegant to me:
First I create an Asset Catalog that wil contain all images for all languages. Every time I add a new Image Asset to the catalog I use a name that represents the language of the image, as shown in the example below:
Below is the code that I use to load an image:
1 |
let image = UIImage(named: NSLocalizedString(“goodMorning", comment:”language independent imageID")) |
But wait….. there is no image with the id “goodMorning” in the Asset Catalog.
I will solve this by using string tables (Localizable.strings) to convert the language independent imageID “goodMorning” into a language specific imageID that is well known in the Asset Catalog.
In my project I have Localizable.strings files for English and Dutch.
The English file contains:
1 |
"goodmorning" = "goodmorning-en"; |
The Dutch file contains:
1 |
"goodmorning" = "goodmorning-nl"; |
From now on my code will pick up the right image for the preferred language.
Problem solved. I can use Asset Catalogs, I do not have to write any custom logic, and I can fully rely on the localisation support of iOS.
I found this solution in the Ray Wenderlich Internatinalization Tutorial