简体   繁体   English

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

[英]NSTextStorage - How to find return chars (new line) in a text

In an NSTextStorage I insert time strings at the current pointer location like this : 在NSTextStorage中,我在当前指针位置插入时间字符串,如下所示:

            NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: @"00:00:00"];
            [attrString autorelease];
            int pos = [self selectedRange].location;
            [[self textStorage] insertAttributedString: attrString atIndex:pos];

So far so good, it works perfect. 到目前为止,效果很好。 But now I want to position the pointer at the beginning of the next line. 但是现在我想将指针放在下一行的开头。 Obviously this is right after the next return char. 显然,这是在下一个返回字符之后。

Now how to find the next return char in textStorage and position the pointer there ? 现在如何在textStorage找到下一个返回char并将指针定位在那里? I have not found any hint in the web for this task. 我在网上没有找到有关此任务的任何提示。 Please help ... 请帮忙 ...

You won't find a method to set the cursor (more precise: selection with zero length) in NSTextStorage 's API, because it is a storage, having no selection. 您不会在NSTextStorage的API中找到设置光标的方法(更精确:长度为零),因为它是一个存储,没有选择。 The selection is a property of the text view. 选择是文本视图的属性。 This is the result of MVC. 这是MVC的结果。 Simply do a check: You can have many text views displaying the same text. 只需检查一下即可:您可以有多个显示相同文本的文本视图。 Obviously each one needs its own selection. 显然,每个人都需要自己选择。

What you have to do is to get the position of the next paragraph (this is better than searching for \\n ) and set this as a selection for the text view. 您要做的是获取下一段的位置(这比搜索\\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);

Typed in Safari, not tested, just to show the basic approach. 在Safari中输入,未经测试,只是为了展示基本方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM