15

I want to go to specify line on my uiwebview loaded. I tried

[webView stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0.0, 100.0)"];

but it's not working. My webview still start with top of the page. I just wonder its because I load the UIWebview inside UIView. Check my code below on my UIView:

- (void)loadView {
    webview = [[WebViewDetail alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];        //initialize a mainView is a UIWebVIew
    webview.managedObjectContext = self.managedObjectContext;
    webview.kitab = self.kitab;
    webview.currentPasal = self.pasal;
    self.title = [NSString stringWithFormat:@"%@ %d", self.kitab, webview.currentPasal];
    self.view=webview;    //make the mainView as the view of this controller    
}

and I put the scroll positioning script on my UIWebView:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    int height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] intValue];

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

in this case I want to put my uiwebview go to the bottom of the page when the view is loaded. But it's totally not working, why? Am I doing it wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
dejoong
  • 2,213
  • 5
  • 25
  • 24

2 Answers2

20

Try

webview.scrollView.contentOffset = CGPointMake(0, 100);
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • i put it on webViewDidFinishLoad in my UIWebView and its not working, the scroll still show top of the page. any other idea? – dejoong Dec 12 '11 at 07:21
  • 2
    @dejoong: are you sure your page is scrollable? try setting it on a timer firing after 1 second, to see if something might scroll after `webViewDidFinishLoad`. – Daniel Dec 12 '11 at 07:36
  • tatz weird Dani, when i fire the method (contain webview.scrollView.contentOffset = CGPointMake(0, 100);) every 1sec its working, but if i call the method directly its not working. do u kno why? – dejoong Dec 12 '11 at 08:15
  • @dejoong: something is scrolling the view after `webViewDidFinishLoad`. I don't know how is that thing working, but I guess there is a later method you can tap to. – Daniel Dec 12 '11 at 13:36
6

Make sure you set the view controller where you have your web view to be a UIWebViewDelegate, and declare this in the @interface of the header file (.h).

[yourWebView setDelegate:self];



Then, in the webViewDidFinishLoad: method, insert this code:

[yourWebView.scrollView scrollRectToVisible:CGRectMake(0, yourWebView.bounds.size.height + 100, 1, 1) animated:NO];           
OscarWyck
  • 2,515
  • 5
  • 21
  • 26