Search code examples
iosobjective-cnsstringcore-text

Double line break being added instead of one


I'm adding a new line into a string as follows:

unichar newLineChar = NSNewLineCharacter;
NSString *newLineCharAsStr = [NSString stringWithCharacters:&newLineChar length:1];
NSString * newLine = [[NSString alloc] initWithString: newLineCharAsStr];
[finalString appendString: newLine];

but the result when rendered in Core Text gives me two line breaks. i.e. an empty line in between two chunks of text. I just want to terminate one line and begin the next one on a new line (i.e. without an empty line between).

If I remove the appendString, then the text flows continuously (i.e. no break added) so I can confirm I'm not accidentally adding a line break twice. I've also tried NSCarriageReturnCharacter, NSLineSeparatorCharacter and NSParagraphSeparatorCharacter as well as \r and \n, but this happens in all cases.

I feel like I'm perhaps looking in the wrong place, but can anyone help?

update: I gather from one of the links provided below that '\n' in Core Text ends a paragraph, inserting a line break below the current line. Which would explain why a line break is always being inserted. So I guess the refined question is, what in Core Text will simply break a line rather than insert a paragraph break? i.e. desired result is

line 1.
line 2.

rather than:

line 1.

line 2.

which is what I'm getting currently.


Solution

  • This is indeed a variant answer on Define Core Text paragraphs without using newline character? as trojanfoe suggested. There's simply no way to force Core Text to treat a new line character as just that and not a paragraph break.

    Consequently, the only way to shrink the paragraph spacing so that '\n' breaks the line only, is to set 'kCTParagraphStyleSpecifierParagraphSpacing' and 'kCTParagraphStyleSpecifierParagraphSpacingBefore' in the Core Text paragraph attributes to 0.0, which is what I did - all looks great now.