Everything about iOS app development

iOS Snippet Monday: Different colors with NSAttributedString

If you are an iOS developer and worked with designers, you would come across this solution that a label displays various colors.

Simplest example is, you need to display a date (Mon. February 27. 2017) but your designer insist on using red color for the day and black for the rest of the text.

How would you do that? Hint: NSAttributedString

There are 2 ways of doing it, but only one of them is awesome.

  1. Using 2 separate labels.
    1. The idea is that you create 2 labels, one for the day, and another one for the rest of the text. In theory it would work fine, but it’s a “lot of work” to get it right, align the labels properly.
  2. Using NSAttributedStrings
    1. Oh yeah baby. This is how you should do it, just one label and custom attributedstrings.

Using NSAttributedString to create multi colored labels

So the idea is that we have a string that needs to be separated into smaller components, so we could apply our colors to each segment. Luckily iOS has a method for this components(separatedBy: ) applies on a string, and expects a string as parameter.

So if you date looks like this: “Mo. Febr. 27, 2017” you could use whitespaces as parameter, to separate the string by each whitespace character, so you would end up with an array like this: [“Mo.”, “Febr.”, “27,”, “2017”].

Than, just use the first component of the array (which we want to use a different color on) and combine the rest of the strings.

As you can see, we take out the first element from the array (firstElement), than join the rest of the array, except the first one = restStrings, and create two separate NSAttributedStrings which we combine into one. (One is an NSMutableAttributedString that we add the other one to).

nsattributedstring ios app swift

This is how it should look like, hope you enjoyed it and learned something.