【问题标题】:On iOS 5, UIWebView is reporting wrong content size for scroll view在 iOS 5 上,UIWebView 报告滚动视图的内容大小错误
【发布时间】:2012-12-25 12:33:47
【问题描述】:

我尝试了一堆“解决方案”,但现在我正试图弄清楚 UIWebView 的滚动视图的内容大小。它目前总是返回 1024,这是设备的宽度。这没有意义,因为我正在查询高度并且视图是纵向的。

以下代码将高度报告为 1024.00000

-(void)webViewDidFinishLoad:(UIWebView *)webView {

  float sourcesWebViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] floatValue];

  NSLog(@"%f", sourcesWebViewHeight);

}

但我只有几行文字。

【问题讨论】:

标签: ios ios5


【解决方案1】:

我将分解最终为我解决此问题的原因。

我必须将我的内容包装在其中。

<html><head><meta name=\"viewport\" content=\"initial-scale=1, user-scalable=no, width=device-width\" /></head><body>%@</body></html>

实现以下视图并加载。

-(void)webViewDidFinishLoad:(UIWebView *)webView {

  [self layoutSubviews];

  webView.scrollView.scrollEnabled = NO;    // Property available in iOS 5.0 and later
  CGRect frame = webView.frame;


  frame.size.height = 1;        // Set the height to a small one.

  webView.frame = frame;       // Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).

  frame.size.height = webView.scrollView.contentSize.height;  // Get the corresponding height from the webView's embedded scrollView.

  webView.frame = frame;





}

-(void) layoutSubviews {
  [super layoutSubviews];
  [body stringByEvaluatingJavaScriptFromString:
   [NSString stringWithFormat:
    @"document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ",
    (int)body.frame.size.width]];
}

最后,我的 webview 做了所有正确的事情,以适应内容。

【讨论】:

  • 我正在为一个 UIWebView 在旋转到纵向后宽度错误而发疯,这可以解决问题!非常感谢
  • 非常老的问题,似乎在 iOS 9 中已修复,但对于 iOS 8 及之前的版本,手动设置 document.querySelector 对我来说是一个诀窍。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 2014-12-28
  • 2013-07-28
相关资源
最近更新 更多