Styling Localized Strings with BonMot

Update – November 2016

BonMot, the library mentioned in this post, has received a significant update, and the code samples presented here are no longer valid. Check out the blog post introducing BonMot 4, which includes a link to the migration guide.

Original Post:

Correct use of localized strings is one of those things, like testing, accessibility, and backups, that you know you should do more of, but it’s fiddly enough to get right that it always seems to be the first to be cut in order to ship on time. On iOS, localization can be particularly annoying when you need to style substrings of a user-facing string. This is because, due to the grammatical differences from language to language, piecing sentences together from individual words can result in a hodgepodge of poor syntax and ambiguity.Logotype for BonMot, the library for beautiful, easy attributed strings for iOS. New in 3.1 is the ability to style localized strings.BonMot, the library I wrote to make styling attributed strings a breeze, just learned a new trick in version 3.1. Thanks to Nora Trapp from Joyable, who submitted a giant pull request to add this feature, you can now use HTML-like tags in your localized strings. You can then use these tags to map BonMot configuration objects to your text.

For example, let’s say we want to style the following string: “I went to Boston, but it was not too cold!” For emphasis, we are bolding the word “not.” To accomplish this with NSAttributedString on its own would be ungainly at best. However, with BonMot, you simply wrap tags around the text you want to style:

This text can go in your Localizable.strings file, or your app can download it from a server. To use it in code, do this:

Look at what happens when we go to localize this string into French: “Je suis allé à Boston, mais il n’était pas trop froid”. The “not” breaks into two parts in French. If you were just searching the main string for the substring representing the word “not” in every language (a common approach that I’ve seen for dealing with cases like this), it would not be sufficient to translate this label into French. However, with BonMot, it’s a breeze. The French version of the localized string looks like this:

When running on a device whose system language is set to French, BonMot will automatically interpret the tags as “Je suis allé à Boston, mais il n’était pas trop fraud!”

For more information on the tag styles feature, check out the ReadMe. A big thanks to Nora for adding this feature. If you’d like to contribute to BonMot, check out the open issues or file one of your own. I look forward to hearing from you!

Do you have a project in mind? We’d love to work with you. If you’d like an opportunity to work on projects with us, check out our Careers page. We’re hiring!

Leave a Comment