Text Attributes on iOS: The effortless approach
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!
- 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?
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.