Search code examples
iosswiftuiscrollviewuikituitextview

Scroll TextView to the top


I have a Text View (UITextView) which displays a long text that is set on runtime like so:

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    if something {
        textView.text = "(very long text here)"
    }

    textView.contentOffset = CGPoint.zero  // doesn't work

}

Unfortunately, when the Text View is displayed, the text is not scrolled to the top but somewhere in the middle.

I'm thinking, either setting the contentOffset is the wrong way of doing it or I am doing it at the wrong time (maybe the text gets changed after setting contentOffset?).

I have tried a lot, I even contacted Apple Code Level Support. They couldn't help me, really (which surprised the hell out of me) – can you?

I'd very much appreciate it. Thank you.


Solution

  • I had a very similar issue, especially when using splitview and testing on the iPhoneX, I resolved this by incorporating this bit of code in my ViewController when I needed the textView to scroll to the top:

    textView.setContentOffset(.zero, animated: false)
    textView.layoutIfNeeded()
    

    If you wish to scroll to the top of the textView upon loading your ViewController:

    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
    
            // Can add an if statement HERE to limit when you wish to scroll to top
            textView.setContentOffset(.zero, animated: false)
    }