Image for post
Image for post

UI Programming

NSAttributedString Unveiled

How to customize the text in your app.

The main way to show some text to the users is through UILabels. Labels let us customize their text with some attributes. Most of us always use the same attributes to customize them.

However, the NSAttributedString API’s offer so many customization possibilities that I took some time to explore them. In today’s article, I’d like to share them with everybody, showing how they behave so that, the next time, we could use the right attribute for the job.

The Base API

Starting from the basics, the first customization point is about changing fonts, font size, and colors. To do that, we need to define the strings to print and a couple of attributes.

The NSAttributedString API comes from Objective-C, a world where typing isn’t as strict as in Swift. However, Swift helps us a bit by adding some type safety. For example, the keys of the attributes dictionary must be of the NSAttributedString.Key type.

In the code, we are creating a first string with the Baskerville font, another with the Chalkduster, increasing the font size and we are painting it orange. We can even change the background, setting it to blue. The result is the following:

Image for post
Image for post

Note: during the rest of the article, I will focus on the code of the attributes, reusing the addLabel function above.

Adjusting the text

Then, there are a set of attributes that let us play with where the letters are rendered within the label. We can play with:

  • the baseline offset
  • the expansion factor
  • the kerning
  • the tracking

Here the code, with the corresponding attributes:

And this is the resulting effect:

Image for post
Image for post

The Subtle Difference Between Tracking and Kerning

As you can see, tracking and kerning look pretty similar to each other. Both of them work on the horizontal spacing of the text you are working with.

The main difference is that the kerning works at the letter level. It defines the distance between characters in the work. From Apple documentation:

Kerning prevents unwanted space from occurring between specific characters and depends on the font.

The tracking, instead, works at the word level. It is used to adjust homogeneously the characters within a word, to avoid unwanted spaces. The Apple documentation does not provide any extra useful information. However, I found this article useful to understand the difference.

Lines

Another customization let us add an underline or strike the text. We can change the color of the strike line and its style. However, even though there are several styles available, only some of them work with UIKit. These are NSUnderlineStyle.single,NSUnderlineStyle.double, andNSUnderlineStyle.thick. The various dash, dot, dashDot, dashDotDot does not seem to work, and neither the byWord style does.

Bonus point for the last style: it allows you to specify a link and it shows the classic appearance of the links, with the custom text underlined. However, given that the UILabel are not controls, the user won’t be able to tap on them… But you can still use the very same attributed string in a UITextField or in a UITextView to enable the tap!

Here the result of the above code. Notice how the underlineColor attribute worked with the link attribute as well.

Image for post
Image for post

Miscellaneous simple attributes

There is a bunch of other attributes that alter the appearance of the text. These are simple attributes: they require us to set a value for specific attributes and then they render the text differently.

These attributes are:

  • obliqueness: as the name implies, this attribute skews the letters by a factor we can specify.
  • effect: this attribute allows us to specify a letterpress effect that makes the letters look like they have been printed.
  • strokeColor and strokeWidth: these attributes color the contour of the text making it transparent inside. We need to specify both the color and the width of the stroke to obtain this effect.

Here the code with these attributes set:

And this is what we can see on the screen after applying them:

Image for post
Image for post

Shadows and Attachments

Moving to more complex attributes, we can do a couple of interesting things with our text.

First, we can add shadows under it. These shadows will follow the shape of the text and can deliver a stunning effect to the user. Here the sample code for that:

As for the other shadows in UIKit, we can control the color, the blurRadius and the shadowOffset. All these properties are set in a NSShadow object. The result is the following:

Image for post
Image for post

Finally, it is possible to add an attachment to the string. Imagine that you want to add a currency into your app, and you want a button that says purchase 10 💎. You can do it with the attachments:

In this case, the process is slightly more complex. We need to:

  • create an NSTextAttachment
  • add the attachment to the attributes for the string
  • create an NSAttributedString for the attachment only
  • create an NSMutableAttributedString with the attributes which contain the attachment
  • compose the two attributed strings
  • finally set them into the label.

The result of this effort is pretty nice:

Image for post
Image for post

Conclusion

Today we explored what we can achieve with NSAttributedStrings. There are a few more attributes that we skipped because they are very rare (the writingDirection, for example, is usually handled by the system).

The big missing attribute is the paragraphStyle: this object allows you to control many aspects of a paragraph, so how a multiline text behaves. For example, it can be used to control line spacing, indentation, and many other things. However, this attribute is slightly complex and it could require an article on its own.

Knowing all these details is really important to understand how the text works on iOS. Nonetheless, using this API is tedious and very error-prone. My suggestion is to use a library that can simplify a lot the NSAttributedString’s customization and can make it easier to work with them. At Bending Spoons, we use BonMot for this purpose: if you are curious about what you can do with it, I strongly encourage you to click on the link and to give it a try!

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Riccardo Cipolleschi

Written by

Hi everybody, I’m Riccardo. Senior iOS Engineer at Bending Spoons, I breathe iOS development: apps and tools. I love to share my knowledge with others.

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Riccardo Cipolleschi

Written by

Hi everybody, I’m Riccardo. Senior iOS Engineer at Bending Spoons, I breathe iOS development: apps and tools. I love to share my knowledge with others.

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store