CSSAttributedString in Swift

5 May 2019

An interesting alternative to managing your NSAttributedStrings in Swift projects. For those who know the CSS styles well.

Motivation

It is just an interesting approach. Maybe for some of you it could be simpler since it seems that everybody knows the CSS styles by heart. Also, it could be useful if you need to share the same styles with the Frontend codebase. I think, there are some cases where it could be helpful, for example when we have a Wikipedia-like page or a document with different headers, different types of text.

Classical approach

This is how it is done classically. We create NSAttributedString and then just add necessary attributes. It is clear that classical doesn’t mean bad. It is typed at least.

CSSAttributedString approach

This is how you can do if you want to change the look of text with the help of CSS.

Make us ready

First of all, you need to add a convenience init method to the NSAttributedString object. So you can initialize attributed strings in a simple way. Here I use the <p></p> tag because it is a basic text element. Don’t forget that the tags could have the default browser styles like the default font for the text. In case of the <p>, it is a block element by default. It means that it always starts on a new line, and fills up the horizontal space to the left and right. Every next element will be rendered below.

So now you can create your styled strings like this. All the properties supported in Safari must be supported here as well! By the way, to use the same font as in iOS you can provide -apple-system, system-ui to the font-family property. So it will automatically use the San-Francisco font. It looks quite nice, huh?

Better structure

Of course, we can go further. We can prepare mappings for our headers, bodies, captions, etc. In case of complex content you can create a whole system for styling with flexbox, etc. I haven’t tested all the CSS properties, so try your hands on.

CSSAttributedString example

You can implement a concatenation method for NSAttributedStrings, so you can join strings with the plus symbol.

Conclusion

So simply experiment with this. And maybe you could find it a good fit to your project. However, have fun!

References

  1. NSAttributedString Apple Documentation
  2. W3Schools CSS reference