user8105388
user8105388

Reputation:

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)

Upvotes: 0

Views: 1568

Answers (2)

ZahraAsgharzade
ZahraAsgharzade

Reputation: 309

you can use this extension :

extension UIScrollView {
    func scrollToTop() {
        let desiredOffset = CGPoint(x: 0, y: -contentInset.top)
        setContentOffset(desiredOffset, animated: true)
    }
}

usage :

textView.scrollToTop()

Upvotes: 0

rmaddy
rmaddy

Reputation: 318794

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)

Upvotes: 3

Related Questions