4

I need to capture the typed text, before rendering, in order to apply some attributes to it.

For that i'm using the delegate method shouldChangeTextInRange of the UITextView along with the NSAttributedString. So far so good, and it works.

The problem is, when the UITextView gets a certain amount of text and it starts scrolling, changing the attributedText makes it scroll to the top, while the next char will make it scroll back to the end.

It keeps on that dance moving up and down while typing..

Setting textview.text, instead of the attributed text, it works n

Any suggestion?

Thanks in advance.

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

    NSAttributedString * newString = [[NSAttributedString alloc] initWithString:text attributes:nil];
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];

    [string insertAttributedString:newString atIndex:range.location];

    textView.attributedText = string;

    range.location += text.length;

    textView.selectedRange = range;

    return NO;
}

2 Answers2

0

I'm not sure about the point of your shouldChangeTextInRange, but to fix the undesired auto-scrolling, try surrounding the setting of textView.attributedText with [textView setScrollEnabled:NO].

That is:

[textView setScrollEnabled:NO];
textView.attributedText = string;
range.location += text.length;
[textView setScrollEnabled:YES];
Smilin Brian
  • 980
  • 8
  • 18
  • I just tried this and it had no effect. I tried saving the scroll position before setting the attributed text, then restoring the previous scroll position, but found that the text view jumps to the top after a delay of around 1 second, after my code had run. This might be the same reason your suggestion didn't work. – arlomedia Oct 04 '13 at 04:07
  • As a test, I disabled scrolling before the text change but didn't reenable it afterwards, and that did stop the scrolling. So the remaining problem is waiting until the iOS does what it does to move the scroll position before reenabling scrolling again. I tried registering for a UITextViewTextDidChangeNotification, but that was called immediately, not after the delay I needed. – arlomedia Oct 04 '13 at 04:36
0
textView.layoutManager.allowsNonContiguousLayout = NO;

Then it will not scroll to the top when changing the attributedText. It works for me.

nathanwhy
  • 5,884
  • 1
  • 12
  • 13