Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll UITextView To Bottom

Tags:

ios

uitextview

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);
like image 838
Jonis Avatar asked May 22 '13 18:05

Jonis


4 Answers

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)
    }
}
like image 158
danypata Avatar answered Nov 18 '22 13:11

danypata


Try this if you have problem on iOS 7 or above. See this SO answer.

- (void)scrollTextViewToBottom:(UITextView *)textView {
    NSRange range = NSMakeRange(textView.text.length, 0);
    [textView scrollRangeToVisible:range];
    // an iOS bug, see https://stackoverflow.com/a/20989956/971070
    [textView setScrollEnabled:NO];
    [textView setScrollEnabled:YES];
}
like image 18
Hong Duan Avatar answered Nov 18 '22 13:11

Hong Duan


With Swift 3

let bottom = self.textView.contentSize.height - self.textView.bounds.size.height
self.textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true)
like image 10
zeeawan Avatar answered Nov 18 '22 13:11

zeeawan


Swift 5

extension UITextView {
    func simple_scrollToBottom() {
        let textCount: Int = text.count
        guard textCount >= 1 else { return }
        scrollRangeToVisible(NSRange(location: textCount - 1, length: 1))
    }
}

// Usage
textView.simple_scrollToBottom()
like image 6
neoneye Avatar answered Nov 18 '22 12:11

neoneye