确定CTLine何时是换行符的结果

时间:2012-10-06 06:56:29

标签: objective-c core-text

我正在尝试确定CTLineRef是否是换行符的结果。我正在使用CTFramesetterCreateFrame来处理所有的换行逻辑(我不是手动创建换行符)。我知道如何做到这一点,但我希望CTLineRef上有某种类型的元数据,具体说明是否是新换行的结果。

示例:

原件:

This is a really long line that goes on for a while.

CTFramesetterCreateFrame应用换行后:

This is a really long line that
goes on for a while.

所以我想确定'持续一段时间'是否是换行的结果。

1 个答案:

答案 0 :(得分:0)

我最终使用了CTLineGetStringRange(CTLineRef)。为了清楚起见;这将返回CTLineRef表示的后备字符串中的位置。之后,它是由CTLineGetStringRange返回的CFRange.location与我的线路位置之间的简单比较。 YMMV取决于您获得特定线路位置的方式。我有一个专门的课程来获取这些信息(详见下文)。

以下是一些代码:

NSUInteger totalLines = 100; // Total number of lines in document.
NSUInteger numVisibleLines = 30; // Number of lines that can fit in the view port.
NSUInteger fromLineNumber = 0; // 0 indexed line number. Add + 1 to get the actual line number

NSUInteger numFormatChars = [[NSString stringWithFormat:@"%d", totalLines] length];
NSString *numFormat = [NSString stringWithFormat:@"%%%dd\n", numFormatChars];
NSMutableString *string = [NSMutableString string];
NSArray *lines = (NSArray *)CTFrameGetLines(textFrame);

for (NSUInteger i = 0; i < numVisibleLines; ++i)
{
    CTLineRef lineRef = (CTLineRef)[lines objectAtIndex:i];
    CFRange range = CTLineGetStringRange(lineRef);

    // This is the object I was referring to that provides me with a line's
    // meta-data. The _document is an instance of a specialized class I use to store
    // meta-data about the document which includes where keywords, variables,
    // numbers, etc. are located within the document. (fyi, this is for a text editor)
    NSUInteger lineLocation = [_document indexOfLineNumber:fromLineNumber];

    // Append the line number.
    if (lineLocation == range.location)
    {
        [string appendFormat:numFormat, actualLineNumber];
        actualLineNumber++;
        fromLine++;
    }
    // This is a continuation of a previous line (wrapped line).
    else
    {
        [string appendString:@"\n"];
    }
}

仅供参考,我没有得到任何答案,因为我已经知道存在CTLineGetStringRange API调用。我希望有一个API调用为我提供了一个布尔值或某些东西,它表明特定的CTLineRef是前一行的延续。