How to set scroll position on uiwebview
20,437
Solution 1
Try
webview.scrollView.contentOffset = CGPointMake(0, 100);
Solution 2
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];
Author by
dejoong
Updated on July 09, 2022Comments
-
dejoong almost 2 years
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
insideUIView
. Check my code below on myUIView
:- (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?
-
dejoong over 12 yearsi put it on webViewDidFinishLoad in my UIWebView and its not working, the scroll still show top of the page. any other idea?
-
Daniel over 12 years@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
. -
dejoong over 12 yearstatz 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?
-
Daniel over 12 years@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. -
slider over 8 yearsiloveyouiloveyouiloveyouiloveyou