Text Attributes on iOS: The effortless approach

Efraim Budusan
mobile appetite
Published in
2 min readDec 20, 2017

Every iOS Developer feels a lump in the throat the moment he finds out 🤯 he has to implement a label with dynamic text looking like this:

You know you’ll have to get your hands dirty with Apple’s NSAttributedStringKeys dictionaries, defining them keys and appending all those AttributesTexts. Oh my… 😱

And you’ll start doing something like this:

And after you finish defining your dictionaries you will start building the AttributedTexts, appending them and finally assigning it to the label.

But…

Xcode has a beautiful attributed text editor built right in the Interface Builder.

This got me wondering 🤔

Why not use it and avoid hardcoding all those attributes in your source files and hardcode them in the xibs instead where you already hardcode a lot of properties anyways.

Yeah, but how will we change those dynamically at runtime?

Simple!

  1. You build your attributed text in the interface builder, as you would with a static one and fill in some placeholders (e.g. <first>) that we will later replace with the actual values, keeping the attributes. Sounds great, right?
<first>, <second> are the placeholders that will be replaced; the placeholders are not required to be in angle brackets and can be any string, though this will make them more unique.

2. You have to define an extension somewhere in your utils files, I named it AttributeString + Replace.

3. Then you effortlessly replace those placeholders with the actual values dynamically at runtime.

And voilà:

I am an iOS developer at tapptitude, a mobile app development agency specialized in building high-quality iOS and Android apps for startups and brands worldwide.

Check out the rest of my gang ->

--

--