ios 如何在uiwebview上设置滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8470991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:50:07  来源:igfitidea点击:

How to set scroll position on uiwebview

iphoneiosobjective-cuiwebview

提问by dejoong

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

我想在加载的 uiwebview 上指定行。我试过

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

[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 UIWebviewinside UIView. Check my code below on my UIView:

但它不起作用。我的 webview 仍然从页面顶部开始。我只是想知道它是因为我加载了UIWebview内部UIView. 在我的下面检查我的代码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:

我把滚动定位脚本放在我的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?

在这种情况下,我想在加载视图时将 uiwebview 放到页面底部。但它完全不起作用,为什么?我做错了吗?

回答by Dani

Try

尝试

webview.scrollView.contentOffset = CGPointMake(0, 100);

回答by OscarWyck

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

确保将 Web 视图所在的视图控制器设置为UIWebViewDelegate,并@interface在头文件 (.h) 中声明。

[yourWebView setDelegate:self];



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



然后,在webViewDidFinishLoad:方法中,插入以下代码:

[yourWebView.scrollView scrollRectToVisible:CGRectMake(0, yourWebView.bounds.size.height + 100, 1, 1) animated:NO];