问题
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?
回答1:
Try
webview.scrollView.contentOffset = CGPointMake(0, 100);
回答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];
来源:https://stackoverflow.com/questions/8470991/how-to-set-scroll-position-on-uiwebview