我正在通过以下调用将内容加载到UIWebView中:
NSString *detailHtmlString = [NSString stringWithFormat:@"<html><head><style>body {background: black;color: white;line-height: 1.4em; font-family: sans-serif; margin: 0; padding: 0 0 30px 0;width: 280px;} p {margin-top: 10px;}</style></head><body id=\"content\">%@</body></html>",[currentWeek objectForKey:@"post_content"]];
[weekDetailController.movie_detail loadHTMLString:detailHtmlString baseURL:nil];
然后,在它完成加载后:
- (void) webViewDidFinishLoad:(UIWebView *)sender {
[self performSelector:@selector(calculateWebViewSize) withObject:nil afterDelay:0.1];
}
- (void) calculateWebViewSize {
[weekDetailController.movie_detail sizeToFit];
float newHeight = [[weekDetailController.movie_detail stringByEvaluatingJavaScriptFromString :@"document.getElementById(\"content\").offsetHeight"] floatValue];
newHeight += 300; //height of the other elements
NSLog(@"Height: %f",newHeight);
CGRect frame = weekDetailController.movie_detail.frame;
NSLog(@"Height was: %f",frame.size.height);
frame.size.height = newHeight;
weekDetailController.movie_detail.frame = frame;
[scrollView.scrollView setContentOffset:CGPointZero];
[scrollView.scrollView setContentSize:CGSizeMake(frame.size.width, frame.size.height)];
}
这在第一次加载视图时效果很好,但在后续视图中,当不同的内容已加载到UIWebView中时(使用与上面相同的调用),获取高度的JavaScript调用返回越来越大的值 - - 即使内容较小,它仍然会返回某个时刻视图中最大内容量的高度。我已经尝试将一个空白的HTML字符串加载到视图中以“清除”它,但这似乎也没有帮助。
任何提示都将不胜感激!
答案 0 :(得分:0)
[scrollView.scrollView setContentOffset:pt];
[scrollView.scrollView setContentSize:CGSizeMake(frame.size.width, frame.size.height)];
您使用的是嵌套的UIScrollViews吗?可能是您只设置内部滚动视图的大小,并将外部滚动视图保留为其内容的最大大小。
编辑:
此外,您应该只使用[scrollView.scrollView setContentOffset:CGPointZero];
答案 1 :(得分:0)
当使用带有约束的嵌套UIWebViews时,您需要重置约束(例如1)并在之后重新加载webview:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, coordinator.transitionDuration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
self.webViewHeightConstraint.constant = 1;
[self reloadWebView]; //[self.webview reload] doesn't work here, simply load with the given url or given html content
});