Localizing pictures and text in iOS

Stefan B
SMG Real Estate Engineering Blog
3 min readDec 21, 2018

--

Lets start with pictures

Recently while working on the app’s latest feature, the Homefeed, we’ve received assets to integrate, in the following form (text was already included for all languages):

We weren’t happy. How were we supposed to use these ? check the current locale and all that ?

Nah, we’ve asked for plain pictures with no text so we can add a localized label ourselves. And got them.

Better.

However, the idea of ‘localizing’ pictures stayed with me.

For loading pictures we used nothing else but the image’s filename in Images.xcassets to pass to UIImage(named name: String).A string that could’ve also come from NSLocalizedString

So if we had an id in the Localizable.string file, we could get different image filenames based on the current locale and the system would do it for us. That’s pretty neat.

Localizable.string (English)
Localizable.string (French)
Localizable.string (German)
Localizable.string (Italian)

Now we could call something like:

let noImageFilename = NSLocalizedString(“noimage.filename.id”, comment: “No Image filename")let noImage = UIImage(named: noImageFilename)

and voilà there’s the localized picture.

Localize text for UILabel in Interface Builder

Generally to add localized text to a UILabel one would need to write something like:

let localizedText = NSLocalizedString("id.of.localized.string", comment: "Some comment")myLabel.text = localizedText

We can set a UILabel’s string in Interface Builder, but wouldn’t it be nice to be able to enter the localized string in IB and never have to write code like above ?

That’s is in fact possible:

extension UILabel {    @IBInspectable var stringId: String {        set(value) {            self.text = NSLocalizedString(value, comment: "")        }        get {            return ""        }    }
}

Adding the above extension on UILabel enables the option to add localized strings in IB already. (using the text’s id from Localizable.strings file)

Summary

These 2 situations could benefit when to support better rendering we don’t want to add extra UI elements and in the latter example help as a shortcut in adding localized strings to UILabel

Hope it helps someone. Thanks for reading.

--

--