MichaelGofron
MichaelGofron

Reputation: 1400

LineCount for attributedString from CoreText is wrong

The linecount for attributed strings from the CoreText foundation appears to be wrong. I used the following code to extract the number of lines that should be present in an attributed string.

 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"\nMe and Me\n" attributes:nil];
    CGPathRef path = CGPathCreateWithRect(CGRectMake(0, 0, 335, 1000000), nil);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), path, NULL);
    NSLog(@"%ld", numberOfLines(frame));


}

static CFIndex numberOfLines(CTFrameRef frame) {
    CGRect bounds = CGRectNull;
    CFArrayRef lines = CTFrameGetLines(frame);
    CFIndex numLines = CFArrayGetCount(lines);
    CGPoint *lineOrigins = malloc((numLines + 1) * sizeof(CGPoint));
    CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), lineOrigins);
    return numLines;
}

I expected the number of lines to be returned to be equal to three. One for the first newline, one for the text "Me and Me", and one for the last newline. Any ideas why it's instead returning 2?

Upvotes: 0

Views: 235

Answers (1)

CRD
CRD

Reputation: 53000

It is simply using the common definition that a line is zero or more characters terminated by a newline.

You can compare the behaviour to standard wc (word count) command run in Terminal. On your sample text it reports 2 lines, 3 words and 11 characters. Adding characters between the final newline and the end of file increases the word & character counts but the line count stays at 2.

HTH

Upvotes: 1

Related Questions