Mac O’Clock
Published in

Mac O’Clock

How to create an attributed UILabel?

Photo by Alvaro Reyes on Unsplash

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.

--

--

--

The best stories for Apple owners and enthusiasts

Recommended from Medium

Export Objects from SAP System to Github Indirectly (ABAPGIT Offline Mode)

Using VIM as a text editing tool on the Mac

How GitHub Codespaces Increase Productivity and Lower Barriers

How to increase Business profits with Mobile App Development?

How to install pgadmin4 — PostgreSQL management tool

Bare Bones Code: When a Graph is a Grid

Startup vs. Corporate vs. Consulting vs. Freelancing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Almost Engineer

Almost Engineer

iOS Software Developer

More from Medium

My iOS Wishlist

Conceptual logo for the latest Apple iPhone operating system, iOS 16

iOS Security: OS Architecture

[Fixed] MacOS Universal Clipboard is not working (Monterey)

Display iPhone camera preview on Watch App