问题
I am having a trivial problem with applying proper top and bottom spacing for the paragraphs in NSAttributedString. I am usng this code to set paragraph attributes:
int sf = sizeof(CGFloat);
CTParagraphStyleSetting settings[ParagraphStylesSupported] =
{
{ kCTParagraphStyleSpecifierAlignment, sizeof(QuartzTextAlignment), &style.textAlignment },
{ kCTParagraphStyleSpecifierParagraphSpacingBefore, sf, &marginTop},
{ kCTParagraphStyleSpecifierParagraphSpacing, sf, &marginBot},
{ kCTParagraphStyleSpecifierMinimumLineHeight, sf, &lineHeight},
{ kCTParagraphStyleSpecifierLineSpacing, sf, &lineSpacing},
{ kCTParagraphStyleSpecifierFirstLineHeadIndent, sf, &style.firstLineIndent},
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, ParagraphStylesSupported);
[string addAttribute:(NSString*)kCTParagraphStyleAttributeName value:(id)paragraphStyle range:item.range];
CFRelease(paragraphStyle);
Text properties are being applied as expected. But there are few problems with paragraph alignment:
- Paragraphs are not being places after each other but flow 'inline' unless there is a newline \n character at the beginning of the attribute range.
- When I add the newline character, then paragraphs are being placed correctly one below another, but newline line height is being added to the spacing 'ParagraphSpacing' gaps.
- kCTParagraphStyleSpecifierParagraphSpacingBefore affects also the newlines character inside the paragraph range.
What Core Text layout engine interprets as a paragraph indicator? Is it every newline character in the attributed string?
回答1:
In Core Text, the newline character (\n
) ends a paragraph. I don't think there is a way to tell it to use a different character.
If you put two newlines in a row, then Core Text will act as if you have an empty paragraph, so it will put in extra spacing.
Make sure you only have one newline after each paragraph. If your paragraphs still have too much space between them, you need to use a smaller value for kCTParagraphStyleSpecifierParagraphSpacingBefore
or kCTParagraphStyleSpecifierParagraphSpacing
(or both).
来源:https://stackoverflow.com/questions/9343787/define-core-text-paragraphs-without-using-newline-character