UITextView not scrolled to top

When populating a UITextView by code, which is typical when the text is not meant to be editable, very long text will not be scrolled to the top. Scrolling in fact seems to be kind of random, but that’s probably because I don’t perceive the rule pattern yet.

If the view is not overlapped by a navbar, then this should do the trick:

Swift 2.3
override func viewDidLayoutSubviews() {  
    super.viewDidLayoutSubviews()  
    dispatch_async(dispatch_get_main_queue(), {  
        self.myTextView.scrollRangeToVisible(NSMakeRange(0, 0))  
    })  
}

If the view is fitted under the navbar of a UINavigationController, then try this:

Swift 2.3
override func viewDidLayoutSubviews() {  
    super.viewDidLayoutSubviews()  
    dispatch_async(dispatch_get_main_queue(), {  
        self.myTextView.contentOffset.y = -self.myTextView.contentInset.top  
    })  
}

h/t

  • https://forums.developer.apple.com/thread/18258