我最终使用了 CTLineGetStringRange(CTLineRef)。只是为了清楚; 这将返回 CTLineRef 表示的支持字符串中的位置。之后,CTLineGetStringRange 返回的 CRange.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 是否是前一行的延续的东西。