Scroll UITextView To Bottom

Jonis picture Jonis · May 22, 2013 · Viewed 28.7k times · Source

I am making a an app that has a UITextView and a button.

When I click the button some text will add in the UITextView.

But when clicking the button, I wan't to scroll down to the bottom of the text field so the user can see the last text added.

How to make the UITextView to scroll down to the bottom?

I tried:

int numLines = LogTextView.contentSize.height / LogTextView.font.lineHeight+1;
NSLog(@"%d",numLines);

NSUInteger length = self.LogTextView.text.length;
self.LogTextView.selectedRange = NSMakeRange(0, length);

but it will not work...

I also tried:

self.LogTextView.contentSize=CGSizeMake(length,0);

Answer

danypata picture danypata · May 22, 2013

You can use the following code if you are talking about UITextView:

-(void)scrollTextViewToBottom:(UITextView *)textView {
     if(textView.text.length > 0 ) {
        NSRange bottom = NSMakeRange(textView.text.length -1, 1);
        [textView scrollRangeToVisible:bottom];
     }

}

SWIFT 4:

func scrollTextViewToBottom(textView: UITextView) {
    if textView.text.count > 0 {
        let location = textView.text.count - 1
        let bottom = NSMakeRange(location, 1)
        textView.scrollRangeToVisible(bottom)
    }
}