我想根据 HTML 内容设置 UIWebview 的高度。我正在获取字符串的大小,但由于段落、粗体、不同的字体大小等原因,我没有得到实际大小。
问问题
20887 次
5 回答
13
我通常使用这些方法将UIWebview
框架设置为内容大小:
- (void)webViewDidStartLoad:(UIWebView *)webView {
CGRect frame = webView.frame;
frame.size.height = 5.0f;
webView.frame = frame;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
CGSize mWebViewTextSize = [webView sizeThatFits:CGSizeMake(1.0f, 1.0f)]; // Pass about any size
CGRect mWebViewFrame = webView.frame;
mWebViewFrame.size.height = mWebViewTextSize.height;
webView.frame = mWebViewFrame;
//Disable bouncing in webview
for (id subview in webView.subviews) {
if ([[subview class] isSubclassOfClass: [UIScrollView class]]) {
[subview setBounces:NO];
}
}
}
当完成加载它的内容时,它们会被自动调用(如果您将webView
' 的委托设置为此类) 。WebView
于 2012-10-16T12:41:39.470 回答
8
好吧,每个 web 视图都有一个内置的 UIScrollView,所以我会尝试等待页面加载,然后点击滚动视图的 contentSize 属性来获取页面的高度。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat height = webView.scrollView.contentSize.height;
}
于 2013-08-08T11:33:08.683 回答
6
试试这个代码
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
height= [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
}
于 2012-10-16T12:58:49.007 回答
1
- (void)viewDidLoad
{
[super viewDidLoad];
webview.delegate = self;
[webview loadHTMLString:@"<div id='foo' style='background: red'>The quick brown fox jumped over the lazy dog.</div>" baseURL:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").offsetHeight;"];
NSLog(@"height: %@", output);
}
于 2012-10-16T12:42:16.850 回答
0
如果您在 tableviewcell 中有 webview,则在 heightForRowAtIndexPath 中将单元格的高度设置为 NSAttributedString 大小的高度,如下所示。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSAttributedString *attributedText = [NSString getHTMLAttributedString:@"HTML Content"];
CGSize size = CGSizeMake(300, CGFLOAT_MAX);
CGRect paragraphRect = [attributedText boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin)
context:nil];
return paragraphRect.size.height;
}
+(NSAttributedString *) getHTMLAttributedString:(NSString *) string{
NSError *errorFees=nil;
NSString *sourceFees = [NSString stringWithFormat:
@"<span style=\"font-family: 'Roboto-Light';font-size: 14px\">%@</span>",string];
NSMutableAttributedString* strFees = [[NSMutableAttributedString alloc] initWithData:[sourceFees dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&errorFees];
return strFees;
}
于 2015-11-04T06:05:49.117 回答