我有一个详细视图,我想要显示文章的标题,副标题和内容。我希望能够使用HTML来格式化文本,所以我使用UIWebView来显示文章正文。这非常有效。
然而,所有这一切都在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,这似乎是正确的:
绿色和蓝色区域的总和值为582像素,但滚动视图仍然只是将504像素区域从导航栏下方滚动到屏幕底部(到标签栏的底部)。
答案 0 :(得分:2)
webview内部有一个滚动视图。您可以按webview.scrollView.contentSize
查询其大小。您必须等待,直到webview完成渲染。
因此,在-webViewDidFinishLoad:
委托方法中,您可以通过webView.scrollView.contentSize.height
获得webView的最佳高度。然后,您可以将webView调整到此高度,并适当地布局其他视图。如果所有这些都是在自定义视图中完成的,那么执行此操作的正确方法可能是在[theView setNeedsLayout]
中调用-layoutSubviews
并覆盖theView
。
您还应将webView.scrollView.alwaysBounceVertically
设置为NO
。
答案 1 :(得分:-2)
我解决了这个问题。
首先,只需将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));
}