How to make sure that words in UILabel won’t be hyphenated?

Florian Hardy
Ideas by Idean
Published in
2 min readMar 10, 2021
The cover of the article

How annoying is it when everything on your screen is perfectly fine… except for this little label that hyphenates words!

Ever been familiar with it?

Important precisions for a good comprehension of this article

  • I need the label to be multiline (numberOfLine equals 2).
  • The label is in a stackview, so there might already be another label (2 lines also) on top of the one that is being displayed.
  • The cell height and width are fixed and can not be stretched.

Let’s take a look at this UICollectionViewCell for instance:

Two cells, on the left is the problem, on the right is the solution

See? That’s a total bummer…
But don’t worry, we can fix it easily thanks to those two UILabel extension methods!

The code

How does it work?

Let’s dive in the main method that I named “adjustLabelSize”:

  1. Save the original style of the UILabel.
  2. Loop through each word to make sure that no word will be hyphenated and displayed two lines. If that is the case, you will have to reduce the size by any value you want, then check again until it’s singleline.
  3. Once the whole text is treated, you can consider that none of your words will be cut. (Well… this part depends on the text to display and could be improved…)
  4. Finally, you can apply the new size to your label, along with its original style.

The second method “actualNumberOfLines” returns the number of lines on which the label will be displayed.

Make the call!

Finally, you just have to call this brand new method on your label, inside the layoutSubview of your cell or view:

For my day-to-day requirements, this works fine, because the text to display is usually not too long (rarely more than 3 or 4 words)… But feel free to adapt those methods to fit your needs.

In the end…

I know this solution is not optimised, and is just a tip for a very specific case that I outlined here.

But if it can help some of us, iOS developers, then my task will not be vain!

Feel free to share your feedback in the comments! And don’t hesitate to tell me if this was helpful.

Thank you for reading.

--

--