20

I have a UILabel that is supposed to be two lines long. The text is localized into French and English.

I'm setting the attributedText property of the label. The text is constructed from three appended strings, say textFragment1, textFragment2 and textFragment3. The middle string is actually an image created with an NSTextAttachment.

I want to make sure that textFragment2 and textFragment3 are on the same line. The first string may or may not wrap depending on how long it is. The problem is that my French text is currently fairly short, so the line is wrapping after textFragment2.

I have fixed this temporarily by adding a line break symbol in the localized French text for textFragment1. I don't really love this solution though. I was wondering if there is a way to treat textFragment2 and textFragment3 so that they will always be together on the same line.

Darren
  • 9,855
  • 18
  • 60
  • 106
  • 4
    Have you tried adding a non-breaking space (`\u00a0`) or a zero-width space (`\u2060`) between textFragment2 and textFragment3? – bdesham Aug 19 '14 at 21:03
  • Works! I had never heard of that before. If you add this as an answer I'll mark it as correct. – Darren Aug 19 '14 at 23:01

1 Answers1

42

You could use a non-breaking space (\u00a0) to join textFragment2 and textFragment3. This character looks just like a normal space—i.e. it results in the same amount of whitespace—but line breaking will not take place on either side of it.

You could also use a zero-width space (\u2060). Using this character will not result in any whitespace, but it will still prevent line breaking on either side. This is what you want if you don’t want any space between textFragment2 and textFragment3 but you still want to prevent line breaking there. (It’s also useful if you have a word with a hyphen in the middle of it but you want to prevent the line from being broken after the hyphen.)

You can read more about these kinds of characters on Wikipedia.

bdesham
  • 13,980
  • 10
  • 70
  • 116