2

I'm currently trying to create an SMS-like screen, where the user can write some text and send it to other users. Everything goes as expected until I try to clear my text view and encounters a crash. I've been trying to find a way around this issue, but I just cannot find enough documentation online. So here it is, and hopefully one of you will know a fix for this.


The implementation

My UITextView is a subclass of Peter Steinberger's implementation for iOS7, and I use it with a custom NSTextStorage subclassed as showed in objc.io's 'Getting to Know TextKit' and especially that source code in order to highlight usernames in the message.

In my ViewController, I configure my text storage like this:

self.textStorage = [[[MyCustomTextStorage alloc] init] autorelease]; [self.textStorage addLayoutManager:self.textView.layoutManager];

And then in my TextView's delegate method:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

I store the input in my custom TextStorage:

[self.textStorage.string stringByReplacingCharactersInRange:range withString:text];

The crash

I can retrieve my text via self.textStorage.string, and then I clear my text view by replacing characters in the range of the input string. This works quite well, but when I try to set my TextView as the first responder again, the application crashes.

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSCFString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:]: Range {5, 0} out of bounds; string length 0'

The range mentioned is the range of my previously cleared string so it looks like I can clear the display, but my TextStorage / TextView is keeping a reference to the first edited range / string.


Any idea on what could be causing this crash and how to resolve it? Thanks for your attention; at this point any help is appreciated, so please feel free to post if you have some piece of advice. :)

4

3 回答 3

0

跟你情况一样。

我花了半天时间解决它。

  1. 你提供的例子是对的。

  2. 您的应用程序不仅会在您清除它时崩溃,而且-setText:每次使用时都会崩溃。

  3. 他们不会崩溃,因为他们永远不会打电话-setText:

解决方案:

将您需要的所有 TextKit 员工添加到您的代码中,

像这样:

_textStorage = [[NSTextStorage alloc] init];
_layoutManager = [[NSLayoutManager alloc] init];
[_textStorage addLayoutManager:_layoutManager];
_textContainer = [[NSTextContainer alloc] init];
[_layoutManager addTextContainer:_textContainer];
_myTextView = [[UITextView alloc] initWithFrame:frame textContainer:_textContainer];

实际上,您错过了NSTextContainer, 所以没有合适的容器可以放入字符串,然后应用程序崩溃了。

也许您可以向这两个演示项目发送拉取请求,以免错过领导其他人。

于 2014-04-17T07:32:37.260 回答
0

它崩溃的原因是因为您使用的范围超出了 textStorage 中字符串的范围。如果你想清除 textView 为什么不使用 self.textStorage.string=@""

于 2014-01-16T04:01:53.803 回答
0

替换文本后,尝试:

[self setSelectedRange:NSMakeRange(0, 0)];
于 2014-10-20T01:33:15.813 回答