Search code examples
iosswiftuitextviewnsrange

How to scroll to top of UITextView?


My code below scrolls all the way to the bottom of the text field. How can I do the reverse of this and have the code function to scroll to the very beginning of the text field?

let bottom = NSMakeRange(theTextView.text.characters.count - 1, 1)
theTextView.scrollRangeToVisible(bottom)

Solution

  • The most obvious solution is to set the location parameter of NSMakeRange to 0 instead of theTextView.text.characters.count - 1.

    let bottom = NSRange(location: 0, length: 1)
    

    A better way is to note that UITextView extends UIScrollView. So you can set the contentOffset:

    theTextView.contentOffset = .zero
    

    If your want to animate the scrolling, use:

    theTextView.setContentOffset(.zero, animated: true)