Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text in UITextView Auto-Scrolled to Bottom

I have what I believe to be a standard UITextView in a ViewController which has a substantial amount of text in it, enough that not all of it can fit on the screen. What I would like to happen is that when that view is loaded, the user can start reading at the top of the text and then scroll down the page as they progress through the text. Makes sense, right? What I want is not unrealistic.

The problem is that when the view loads, the text in the UITextView is already scrolled all the way down to the bottom. I have scoured SO and there are a number of similar posts but none of the solutions therein are resolving my problem. Here is the code in he view controller:

import UIKit

class WelcomeTextVC: UIViewController {

    var textString: String = ""

    @IBOutlet weak var welcomeText: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.translucent = false

        self.welcomeText.text = textString
        self.welcomeText.scrollRangeToVisible(NSMakeRange(0, 0))
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)

        self.welcomeText.scrollRangeToVisible(NSMakeRange(0, 0))
        welcomeText.setContentOffset(CGPointMake(0, -self.welcomeText.contentInset.top), animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I have tried most of the standard solutions to no avail. The one common suggestion which I have not tried is to "Uncheck the Adjust Scroll View Insets in the Attributes Inspector". The reason I have not tried it is because I cannot locate this fabled check box.

What do I need to do to make the text start out aligned to the top?

like image 648
zeeple Avatar asked Oct 31 '15 03:10

zeeple


1 Answers

There's a couple ways I know of. Both ways are implemented programmatically through the viewDidLayoutSubviews() method in your view controller. After the call to super.viewDidLayoutSubviews(), you could add:

myTextView.scrollRangeToVisible(NSMakeRange(0, 1))

This would automatically scroll the textView to the first character in the textView. That however might add some unwanted animation when the view appears. The second way would be by adding:

myTextView.setContentOffset(CGPoint.zero, animated: false)

This scrolls the UITextView to point zero (the beginning) and gives you control over whether you want it animated or not.

like image 74
Aaron Avatar answered Sep 27 '22 23:09

Aaron