Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I scroll programmatically to the bottom in a UIWebView?

I know a similar question has been asked before but it seemed never been answered. I have a UIWebView and add some content by string. I use UIWebView because I add some images to it dynamically and also use other HTML features. This example code is simplified.

NSString *myHtmlString = @"SOME LONG TEST STRING 1234567890 123456789 0123456789 0123456789 0123456789 01234567890 WWWWWWWWWW WWWWWWWWWW WWWYYYYYYY YYYYYYYYYY YYYYYYYYYY YYYYYYYYYY YYYYYYYYYY YYYYYYYYY YYYYYYYWWW WWWWWWWWWW WWWWWWWWWW WWWXXXXXXX XXXXXXXXXX XXXZZZZZZZ THIS IS THE END I WANT TO SEE";
NSString *myPath = [[NSBundle mainBundle] bundlePath];
NSURL *myBaseURL = [NSURL fileURLWithPath:myPath];
[myWebView loadHTMLString:myHtmlString baseURL:myBaseURL];

What I want to see is the end of the string. I can scroll there, no problem. But I want to go there programatically.

like image 595
hol Avatar asked Aug 29 '10 13:08

hol


3 Answers

This is fairly simple. First, you'll need to obtain height of the webpage:

NSInteger height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] intValue];

Now you have the height of the document stored in the height variable. To scroll to bottom you have to use javascript again:

NSString* javascript = [NSString stringWithFormat:@"window.scrollBy(0, %d);", height];   
[webView stringByEvaluatingJavaScriptFromString:javascript];

Of course you need to call them in proper moment. That is

– webViewDidFinishLoad:(UIWebView *)webView

method of your webview delegate.

like image 73
Pawel Avatar answered Nov 01 '22 15:11

Pawel


in iOS 5+ you could call the following method from your -(void)webViewDidFinishLoad:(UIWebView *)webView

- (void)webViewScrollToBottom:(UIWebView *)webView
{
    CGFloat scrollHeight = webView.scrollView.contentSize.height - webView.bounds.size.height;
    if (0.0f > scrollHeight)
        scrollHeight = 0.0f;
    webView.scrollView.contentOffset = CGPointMake(0.0f, scrollHeight);
}
like image 35
demosten Avatar answered Nov 01 '22 15:11

demosten


This is how you can scroll down Animated:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
        CGPoint bottomOffset = CGPointMake(0, self.myWebView.scrollView.contentSize.height - self.myWebView.scrollView.bounds.size.height);
        [self.myWebView.scrollView setContentOffset:bottomOffset animated:YES];
}
like image 25
Oded Regev Avatar answered Nov 01 '22 14:11

Oded Regev