iOS: Indent first line of UILabel for a custom view

Ngo Minh Tri
3 min readSep 25, 2021

If you notice, the orange promotion message has two lines of text not aligned to the left. In front of the promotion’s first line, there is a crown icon. To implement that, we can use NSTextAttachment to attach an image inline of text.

It is the same with the promotion message; the movie name has two lines of text not aligned to the left. In front of the movie name’s first line, a bit difference is a custom view, not an image. I can’t use NSTextAttachment anymore unless I create a custom view, convert it to UIImage, and reuse the above code. But this idea is not good in performance and scalability.

After few rounds of searching, I found firstLineHeadIndent might be helpful. The custom view will anchor to the top-left of the movie name; then, the indent will be equal to the width of the custom view.

1. First, I create a custom view TagView with title and color as require properties.

2. Staying inside TagView, I create another property to return an actual width based on the text length using intrinsicContentSize.width. Please take note of this property which I am going to use for firstLineHeadIndent later on.

3. Moving to the ViewController, I create two popular & new tag views and a stack view as a container of multiple tags.

4. I add popular & new tag subviews into the container stack view. By auto layout, I anchor the tagStackView to the top-left of movieNameLabel.

5. This is the most important step; let calculate how much the first line indent will be.

  • Map all stack subviews to TagView instance.
  • Map each of TagView to their width, which I already implemented.
  • Sum all the TagView width together with the spacing. Tada 🎉

6. Finally, I have the TagView width. I use that value for firstLineHeadIndent

As you observe, the popular & new tags are in different layers with the movie name, and it overlaps the movie name rectangle frame. However, the crown 👑 is in the same layer as promotion message.

If you have a better idea, please share it. I am happy to study.

Thanks for reading, and happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ngo Minh Tri
Ngo Minh Tri

Written by Ngo Minh Tri

Wherever you go, go with all your heart.

No responses yet

Write a response