我想根据HTML内容设置UIWebview的高度。我得到一个字符串的大小,但由于段落,粗体,不同的字体大小等而没有得到实际大小。
答案 0 :(得分: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
的委托设置为此类)。
答案 1 :(得分:9)
好吧,每个Web视图都内置了一个UIScrollView,所以我会尝试等待页面加载,然后点击滚动视图的contentSize属性来获取页面的高度。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat height = webView.scrollView.contentSize.height;
}
答案 2 :(得分:7)
试试此代码
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
height= [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
}
答案 3 :(得分: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);
}
另见How to determine UIWebView height based on content, within a variable height UITableView?
答案 4 :(得分: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;
}