How to create an attributed UILabel?
It is a simple tutorial for people who don’t like to work with attributed text, but sometimes you just need to do because of your design. Now I will show you the most used attributed properties and how to collect one label with a few styles, fonts, font sizes, colors, etc. I will try to answer on common attributed string questions like:
- How to create a bold part of String?
- How to create a different color part of String?
- How to create an underline String or part of String?
- How to create a strikethrough color String?
- How to create a space between letters in String?
Worked example on Github
Our goal to create a UILabel like below:
So here we have 3 parts – “Mr”, “John”, “Doe”. We need an NSAttributedString instead of default String type here. NSAttributedString can have a dictionary with unique attributes [NSAttributedString.Key: Any]. We need to set these dictionaries for all our parts.
The mrAttributes dictionary styles the “Mr.” part, nameAttributes for the “John” part and lastNameAttributes for the “Doe” part.
Now we can merge these 3 NSAttributedStrings. But the fact is we can’t because one of them must be an NSMutableAttributedString.
As a result, we have the mrString which contains all 3 parts.