How to set scroll position on uiwebview

房东的猫 提交于 2019-11-29 06:25:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!