Marian Stiehler
Marian Stiehler

Reputation: 157

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.

Upvotes: 1

Views: 611

Answers (3)

redribben
redribben

Reputation: 186

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)
}

Upvotes: 2

MwcsMac
MwcsMac

Reputation: 7168

You need to use viewDidLayoutSubviews() so that it set the scrollview to the top.

override func viewDidLayoutSubviews() {
   textView.setContentOffset(.zero, animated: false)
}

Upvotes: 0

klememi
klememi

Reputation: 116

You may need to write more information/code because if you try this piece of code in clean project with only one VC with UITextView, you'll see that it's actually working. If you're really using some condition (if something) this might be the issue. What is this something in your real code?

Upvotes: 0

Related Questions