现在,我可以通过使用具有段落粒度的标记器循环来获取包含 n 行的 UITextView 中每一行的文本范围。不幸的是,这意味着我对文本中第 m 行的搜索算法是 n 阶的。除了让我的算法 log n 之外,还有什么更简单的方法可以找到范围吗?以下是我现在如何找到我的文本范围:
- (UITextRange *)textRangeOfLineAtIndex:(NSUInteger)index {
UITextPosition *position = self.beginningOfDocument;
NSUInteger lineCount = 0;
while([self comparePosition:self.endOfDocument toPosition:position] == NSOrderedDescending && lineCount < index) {
position = [self.tokenizer positionFromPosition:position toBoundary:UITextGranularityParagraph inDirection:UITextStorageDirectionForward];
++lineCount;
}
return [self rangeEnclosingPosition:position withGranularity:UITextGranularityParagraph inDirection:UITextStorageDirectionForward];
}