Skip to content

Before-after attributes

Many times, in our apps, we want not just to have plain old strings. We want to apply some attributes to them.

For example, instead of just having this string:

This string contains bold elements as well as italic elements.

We want it to be more visually descriptive, i.e. to look like this:

This string contains bold elements as well as italic elements.

In order to achieve this, Apple gave us the:

1
NSAttributedString

So, in order for us make this in code we have to do this:

1
2
3
4
5
6
7
8
9
10
11
let attributedString = NSMutableAttributedString(string: "This string contains bold elements as well as italic elements.\n")

let attributes1: [NSAttributedStringKey : Any] = [
.font: UIFont(name: "HelveticaNeue-Bold", size: 13)!
]
attributedString.addAttributes(attributes1, range: NSRange(location: 21, length: 4))

let attributes3: [NSAttributedStringKey : Any] = [
.font: UIFont(name: "HelveticaNeue-Italic", size: 13)!
]
attributedString.addAttributes(attributes3, range: NSRange(location: 46, length: 6))

That is awesome!

But…

We have a problem…

Working with NSRange is very tedious job. You have to count characters, you have to try it a couple of times, etc. Boooo, boring!

Well, there is a way:

 

Check out this link: https://andresinaka.github.io/Transformer.

Wait… is it possible? Yes 🙂

In short, if you need to pre-format attributed strings for labels or other elements in your app, this tool is so helpful.

End result:

As you can see, you get the whole source code which you can copy-paste into your Xcode project.

Happy coding! Have fun with some attributes! Have a fun day!

Published iniOSTools

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: