0

我正在尝试制作一个 tumblr 应用程序。当我对任何帖子发出获取请求时,他们会返回正文的 html。目前我正在使用 html 并将其推入 uiwebview。我设置了视图的宽度,因为它总是相同的,但我不知道如何计算它的高度。我正在尝试将其放入 uitable 中,因此我需要计算出每个单元格的高度。

所以基本上可以在渲染html后获得uiwebview的高度吗?

4

1 回答 1

2

我使用 javascript 技巧来做到这一点。

在将 HTML 字符串加载到 UIWebView 之前,您需要将以下 javascript 添加到 HTML 字符串中。

NSMutableString *javaScript = [[NSMutableString alloc] init];
[javaScript appendString:@"<script type=\"text/javascript\">"];
[javaScript appendString:@"  window.onload = function() {"];
[javaScript appendString:@"    window.location.href = \"ready://\" + document.body.offsetHeight;"];
[javaScript appendString:@"  }"];
[javaScript appendString:@"</script>"];

当 UIWebView 完成渲染并知道所需的 UIWebView 高度以显示整个内容而无需上下滚动时,将触发此 javascript。高度由 javascript 变量 document.body.offsetHeight 给出

javascript 会将 UIWebView 导航到准备好的 url 方案://

document.body.offsetHeight 的值存储为“主机”

您必须使用 UIWebView 委托拦截此请求,以便 UIWebView 不会导航到 ready://

- (BOOL)webView:(UIWebView*)webView
shouldStartLoadWithRequest:(NSURLRequest*)request
 navigationType:(UIWebViewNavigationType)navigationType {

    NSURL *url = [request URL];
    if (navigationType == UIWebViewNavigationTypeOther) {
        if ([[url scheme] isEqualToString:@"ready"]) {

            float contentHeight = [[url host] floatValue];
            NSLog(@"web height:%f",contentHeight);

            //You can use the contentHeight to resize the UIWebView frame



            return NO; //Prevent the UIWebView to navigate to this ready:// scheme
        }
    }
    return YES;
}

“就绪”方案只是一个任意名称。基本上,JavaScript 要求 UIWebView 导航到 ready://234

“就绪”是自定义 URL 方案

“234”是 UIWebView 在不滚动的情况下呈现 HTML 内容所需高度的示例。

于 2012-11-09T07:37:58.747 回答