NSTextStorage - 如何在文本中查找返回字符(换行符)

时间:2015-12-01 05:56:39

标签: objective-c nstextstorage

在NSTextStorage中,我在当前指针位置插入时间字符串,如下所示:

Copy Local=true

到目前为止一切顺利,它完美无缺。但是现在我想把指针放在下一行的开头。显然这是在下一个返回char之后。

现在如何找到 NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: @"00:00:00"]; [attrString autorelease]; int pos = [self selectedRange].location; [[self textStorage] insertAttributedString: attrString atIndex:pos]; 中的下一个返回字符并将指针放在那里? 我没有在网上找到任何关于此任务的提示。请帮忙......

1 个答案:

答案 0 :(得分:0)

您在NSTextStorage的API中找不到设置光标的方法(更精确:选择零长度),因为它是一个没有选择的存储。选择是文本视图的属性。这是MVC的结果。只需进行检查:您可以有许多文本视图显示相同的文本。显然每个人都需要自己选择。

您需要做的是获取下一段的位置(这比搜索\n更好)并将其设置为文本视图的选择。

NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: @"00:00:00"];
[attrString autorelease]; // You should *really* use ARC
int pos = [self selectedRange].location;
[[self textStorage] insertAttributedString: attrString atIndex:pos];

// Get the next paragraph
NSString *text = self.textStorage.string;
NSRange restOfStringRange = NSMakeRange( pos, [text length]-pos );
NSUInteger nextParagraphIndex;

// You have to look to the start of the next paragraph
[text getParagraphStart:&nextParagraphIndex end:NULL contentsEnd:NULL forRange:restOfStringRange];

NSTextView *view = self.textView; // Or where ever you get it from
view.selectedRange = NSMakeRange(nextParagraphIndex, 0);

输入Safari,未经过测试,只是为了显示基本方法。