使用UIWebView确定UIScrollView的高度

我有一个详细视图,我想要显示文章的标题,副标题和内容。 我希望能够使用HTML来格式化文本,所以我使用UIWebView来显示文章正文。 这非常有效。

但是,所有这一切都在UIScrollView中,所以我的问题是我必须计算UIScrollView的高度?

这是它今天的工作方式:

UIScrollView中

这就是它在Storyboard中的样子:

故事板

所以我需要知道的是,计算UIScrollView正确高度的正确代码和语法是什么? 在几件事情中,我试过[self.scrollView sizeToFit]没有运气。

编辑:显然它使用下面的代码设置正确的高度,但似乎视图永远不会更新。

 -(void)webViewDidFinishLoad:(UIWebView *)webView { // get height of content in webview CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue]; // set new frame height CGRect frame = webView.frame; frame.size.height = height; webView.frame = frame; // webview is now correct height // set new frame height for scrollview (parent of webview) CGRect scrollFrame = self.scrollView.frame; scrollFrame.size.height = webView.frame.origin.y + height; self.scrollView.frame = scrollFrame; // log to console for cross checking NSLog(@"new frame: %f, scrollview frame: %f", scrollFrame.size.height, self.scrollView.frame.size.height); } 

控制台报告明显正确的高度:

new frame: 582.000000, scrollview frame: 582.000000

并快速检查Photoshop,这似乎是正确的:

scrollview的屏幕截图

绿色和蓝色区域的总和值为582像素,但滚动视图仍然只是将504像素区域从导航栏下方滚动到屏幕底部(到标签栏的底部)。

webview内部有一个滚动视图。 您可以通过webview.scrollView.contentSize查询其大小。 您必须等待,直到webview完成渲染。

因此,在-webViewDidFinishLoad: delegate方法中,您可以通过-webViewDidFinishLoad:获取webView的最佳高度。 然后,您可以将webView调整到此高度,并适当地布局其他视图。 如果所有这些都是在自定义视图中完成的,那么执行此操作的正确方法可能是在视图中调用[theView setNeedsLayout]并覆盖theView

您还应将webView.scrollView.alwaysBounceVertically设置为NO

我解决了这个问题。

首先,只需将UIWebView扩展到高于内容的高度(例如2000像素)。

使魔法发生的委托方法代码

 -(void)webViewDidFinishLoad:(UIWebView *)webView { // set height for webiew webView.autoresizesSubviews = NO; webView.translatesAutoresizingMaskIntoConstraints = YES; webView.scrollView.autoresizesSubviews = NO; webView.scrollView.translatesAutoresizingMaskIntoConstraints = YES; CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').clientHeight;"] floatValue] + 80; // +80 for tabbar and spacing CGRect frame = webView.frame; frame.size.height = height; webView.frame = frame; // fix height of scroll view as well self.scrollView.translatesAutoresizingMaskIntoConstraints = YES; self.scrollView.contentSize = CGSizeMake(320, (self.webView.frame.origin.y + self.webView.frame.size.height)); }