iosobjective-cswiftxcodecocoa-touch

UITextView starts at Bottom or Middle of the text


I'll get right to it. I have a UItextView placed in my view that when needs to scroll to see all the text (when a lot of text is present in the textView) the textView starts in the middle of the text sometimes and the bottom of the text other times.

enter image description here

Editing is not enabled on the textView. I need a way to force the textView to start at the top, every time. I saw some questions somewhat like this where other people used a content offset, but I do not really know how that works or if it would even be applicable here.

Thanks for your help.


Solution

  • This did the trick for me!

    Objective C:

    [self.textView scrollRangeToVisible:NSMakeRange(0, 0)];
    

    Swift:

    self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
    

    Swift 2 (Alternate Solution)

    Add this override method to your ViewController

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

    Swift 3 & 4 (syntax edit)

    override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      
      textView.contentOffset = .zero
    }