代码之家  ›  专栏  ›  技术社区  ›  Emil

uiwebview-autoresize以便不需要滚动(在webview本身中)

  •  9
  • Emil  · 技术社区  · 14 年前

    我想用一个 UIWebView 用于显示高于iPhone屏幕的内容,无需滚动 UIWebVIEW 本身。

    这个 UIWebVIEW 作为子视图放置到 UIScrollView 以及其他一些我想要的对象 UISCLVIEW 上下滚动 具有 这个 UIWebVIEW .

    我知道你可以用 UITextView 这样地:

    CGRect frame = _textView.frame; frame.size.height = _textView.contentSize.height; _textView.frame = frame;
    

    但是 UIWebVIEW 不从继承 UISCLVIEW 因此不包含 contentSize -性质。

    我真的很想保留它 UIWebVIEW ,因为我得到的数据是HTML块。

    谢谢您!

    2 回复  |  直到 14 年前
        1
  •  7
  •   Daniel    14 年前

    我认为唯一能做到这一点的方法是使用一些javascript来获取网页的大小并调整uiwebview控件的大小。

    像下面这样的技巧就可以了

    int content_height = [[theWebView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] integerValue];
    CGRect rect = theWebView.frame;
    rect.size.height = content_height;
    theWebView.frame = rect;
    

    您可能需要在内容高度中添加某种软糖因子。

        2
  •  14
  •   jv42    14 年前

    实际上,不需要JavaScript! 在uiview中有一个很好的方法:

    - (CGSize)sizeThatFits:(CGSize)size
    

    传递给它任何东西(这里没有真正意义),它返回它想要的大小,使用其内容(子视图等)计算大小。

    当然,由于在异步的uiWebView中加载内容,因此应该在加载了WebView后执行此操作,例如在uiWebView委托方法中:

    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        CGSize size = [webView sizeThatFits: CGSizeMake(1.0f, 1.0f)]; // Pass about any size
        CGRect frame = webView.frame;
        frame.size.height = size.height;
        webView.frame = frame;
    }
    

    瞧!