Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force a UITextView to scroll to the top every time I change the text?

OK, I'm having some problem with the UITextView. Here's the issue:

I add some text to a UITextView. The user then double clicks to select something. I then change the text in the UITextView (programatically as above) and the UITextView scrolls to the bottom of the page where there is a cursor.

However, that is NOT where the user clicked. It ALWAYS scrolls to the bottom of the UITextView regardless of where the user clicked.

So here's my question: How do I force the UITextView to scroll to the top every time I change the text? I've tried contentOffset and scrollRangeToVisible. Neither work.

Any suggestions would be appreciated.

like image 618
Sam Stewart Avatar asked Aug 05 '09 16:08

Sam Stewart


4 Answers

UITextView*note;
[note setContentOffset:CGPointZero animated:YES];

This does it for me.

Swift version (Swift 4.1 with iOS 11 on Xcode 9.3):

note.setContentOffset(.zero, animated: true)
like image 137
Wayne Lo Avatar answered Oct 14 '22 19:10

Wayne Lo


If anyone has this problem in iOS 8, I found that just setting the UITextView's text property, then calling scrollRangeToVisible with an NSRange with location:0, length:0, worked. My text view was not editable, and I tested both selectable and not selectable (neither setting affected the result). Here's a Swift example:

myTextView.text = "Text that is long enough to scroll"
myTextView.scrollRangeToVisible(NSRange(location:0, length:0))
like image 44
nerd2know Avatar answered Oct 14 '22 17:10

nerd2know


And here is my solution...

    override func viewDidLoad() {
        textView.scrollEnabled = false
        textView.text = "your text"
    }

    override func viewDidAppear(animated: Bool) {
        textView.scrollEnabled = true
    }
like image 46
miguel Avatar answered Oct 14 '22 19:10

miguel


Calling

scrollRangeToVisible(NSMakeRange(0, 0))

works but call it in

override func viewDidAppear(animated: Bool)
like image 39
RyanTCB Avatar answered Oct 14 '22 18:10

RyanTCB