在UIScrollView中实现UIWebView

我试图在UIScrollView中使用UIWebView,我想显示一个图像下的webview,使他们可以滚动。 所以我走了那些步骤:

  1. 取消激活UIWebView的滚动属性
  2. 设置UIScrollView和UIWebView高度等于内容大小。

而这个我的代码:

- (void)viewDidLoad { [super viewDidLoad]; self.contentReader.scrollView.scrollEnabled = NO; NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n" "<head> \n" "<style type=\"text/css\"> \n" "body {font-family: \"%@\"; font-size: %d;}\n" "</style> \n" "</head> \n" "<body>%@</body> \n" "</html>", @"JF Flat", 18, self.thePost.content]; [self.contentReader loadHTMLString:[NSString stringWithFormat:@"<div style='text-align:right; text-align:justify; direction:rtl'><style type='text/css'>img { max-width: 100%%; width: auto; height: auto; }</style><style type='text/css'>iframe { max-width: 100%%; width: auto; height: auto; }</style>%@<div>",myDescriptionHTML] baseURL:nil]; } -(void)webViewDidFinishLoad:(UIWebView *)webView { // get the html content height NSString *output = [webView stringByEvaluatingJavaScriptFromString:@"document.height;"]; NSLog(@"Content Size %@",output); // adjust the height of webView NSLog(@"WebView Hieght before Update%f", webView.frame.size.height); CGRect frame = webView.frame; frame.size.height = 1; webView.frame = frame; CGSize fittingSize = [webView sizeThatFits:CGSizeZero]; frame.size = fittingSize; webView.frame = frame; NSLog(@"WebView Hieght After Update%f", webView.frame.size.height); [self.scroller setContentSize:webView.bounds.size]; } 

这是日志消息:

 [5150:203791] WebView Hieght before Update360.000000 [5150:203791] WebView Hieght After Update5888.000000 

问题是,当我向下滚动的内容没有显示,什么都不显示。 检查图片: 在这里输入图像说明

更新debugging视图Hearachy。 在这里输入图像说明

正如您所看到的,视图层次结构中的WebView高度没有改变。 只有网页已经改变了大小。

我们已经在评论中解决了这个问题,所以我们只是为了完整性而提出这个答案。

如果您使用自动布局,请确保通过设置约束(如高度约束)并更改其常量以更改布局来更改WebView的大小。 如果你想animation一个特定的自动布局改变,做这样的事情:

 [UIView animateWithDuration:0.5 animations:^{ self.webViewHeightConstraint.constant = fittingSize.height; [self.view layoutIfNeeded]; }]; 

有点远,但你可能想尝试

 webView.scrollView.contentSize = fittingSize; 

要么

 webView.scrollView.frame = CGRectMake(0,0,fittingSize.width, fittingSize.height); 

由于滚动被closures,所以在加载html之后,内容大小或帧可能不会改变。 就像我说了一个远射,但可能工作。