How to keep a UITextView scrolled to the bottom

UITextViews are ideal for displaying large amounts of scrollable text on a small screen, or a portion of the screen. They’re also great for continuously adding text to them, which naturally appears at the bottom. However, doing so does not scroll the text upwards so that the user can see the latest addition by default.

To accomplish this, many sources suggest to add use the contentOffset property. While this works if another component (like a keyboard) may come into vision, it does not help to steady keep all the text in our text view at the bottom at all times. However, another method from the UITextView class can help us there: scrollRangeToVisible.

To use it, we need to define an NSRange struct and define the portion of the text content that we’d like to display. We don’t need to find out what the height of our text view is for this, it is indeed enough to simply specify the last line of our text content. The following code nippet will do that:

- (void)positionTextView {
    // scroll to the bottom of the content
    NSRange lastLine = NSMakeRange(self.textView.text.length - 1, 1);
    [self.textView scrollRangeToVisible:lastLine];

Call this whenever text is added to the text view, or changes to the text view arise from constraint changes, and your last line of text will always be scrolled to the bottom.

Leave a Reply