Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what to use instead of scrollRangeToVisible in iOS7 or TextKit

In previous versions of iOS, my UITextView will scroll to the bottom using

[displayText scrollRangeToVisible:NSMakeRange(0,[displayText.text length])];

or

CGFloat topCorrect = displayText.contentSize.height -[displayText bounds].size.height;
topCorrect = (topCorrect<0.0?0.0:topCorrect);
displayText.contentOffset = (CGPoint){.x=0, .y=topCorrect};

But the former will now have the weird effect of starting at the top of a long length of text and animating the scroll to the bottom each time I append text to the view. Is there a way to pop down to the bottom of the text when I add text?

like image 716
Nelson Ko Avatar asked Nov 26 '13 18:11

Nelson Ko


3 Answers

textView.scrollEnabled = NO;
[textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1,0)];
textView.scrollEnabled = YES;

This really works for me in iOS 7.1.2.

like image 96
user3907849 Avatar answered Oct 20 '22 00:10

user3907849


For future travelers, building off of @mikeho's post, I found something that worked wonders for me, but is a bit simpler.

1) Be sure your UITextView's contentInsets are properly set & your textView is already firstResponder() before doing this.
2) After my the insets are ready to go, and the cursor is active, I call the following function:

private func scrollToCursorPosition() {
    let caret = textView.caretRectForPosition(textView.selectedTextRange!.start)
    let keyboardTopBorder = textView.bounds.size.height - keyboardHeight!

   // Remember, the y-scale starts in the upper-left hand corner at "0", then gets
   // larger as you go down the screen from top-to-bottom. Therefore, the caret.origin.y
   // being larger than keyboardTopBorder indicates that the caret sits below the
   // keyboardTopBorder, and the textView needs to scroll to the position.
   if caret.origin.y > keyboardTopBorder {
        textView.scrollRectToVisible(caret, animated: true)
    }
 }
like image 35
kbpontius Avatar answered Oct 19 '22 22:10

kbpontius


I believe this is a bug in iOS 7. Toggling scrollEnabled on the UITextView seems to fix it:

[displayText scrollRangeToVisible:NSMakeRange(0,[displayText.text length])];
displayText.scrollEnabled = NO;
displayText.scrollEnabled = YES;
like image 28
Peter Heide Avatar answered Oct 19 '22 23:10

Peter Heide