Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView setText should not jump to top in ios8

Following iOS 8 code is called every second:

- (void)appendString(NSString *)newString toTextView:(UITextView *)textView {
    textView.scrollEnabled = NO;
    textView.text = [NSString stringWithFormat:@"%@%@%@", textView.text, newString, @"\n"];
    textView.scrollEnabled = YES;
    [textView scrollRangeToVisible:NSMakeRange(textView.text.length, 0)];
}

The goal is to have the same scrolling down behaviour as the XCode console when the text starts running off the bottom. Unfortunately, setText causes the view to reset to the top before I can scroll down again with scrollRangeToVisible.

This was solved in iOS7 with the above code and it worked, but after upgrading last week to iOS8, that solution no longer seems to work anymore.

I can't figure out how to get this going fluently without the jumping behaviour?

like image 380
Wouter Scholtens Avatar asked Sep 25 '14 11:09

Wouter Scholtens


2 Answers

I meet this problem too. You can try this.

textView.layoutManager.allowsNonContiguousLayout = NO;

refrence:http://hayatomo.com/2014/09/26/1307

like image 124
frank Avatar answered Jan 03 '23 16:01

frank


The following two solutions don't work for me on iOS 8.0.

textView.scrollEnabled = NO;
[textView.setText: text];
textView.scrollEnabled = YES;

and

CGPoint offset = textView.contentOffset;
[textView.setText: text];
[textView setContentOffset:offset];

I setup a delegate to the textview to monitor the scroll event, and noticed that after my operation to restore the offset, the offset is reset to 0 again. So I instead use the main operation queue to make sure my restore operation happens after the "reset to 0" option.

Here's my solution that works for iOS 8.0.

CGPoint offset = self.textView.contentOffset;
self.textView.attributedText = replace;
[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
    [self.textView setContentOffset: offset];
}];
like image 43
Harper Avatar answered Jan 03 '23 15:01

Harper