![](/img/trans.png)
[英]How to determine UIWebView height based on content, within a variable height UITableView?
[英]How to set height of UIWebView based on html content?
我想根據HTML內容設置UIWebview的高度。 我得到一個字符串的大小,但由於段落,粗體,不同的字體大小等,沒有得到實際的大小。
我通常使用這些方法來設置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
的委托設置為此類)。
好吧,每個Web視圖都內置了一個UIScrollView,所以我會嘗試等待頁面加載,然后點擊滾動視圖的contentSize屬性來獲取頁面的高度。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat height = webView.scrollView.contentSize.height;
}
試試這個代碼
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
height= [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
}
- (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);
}
如果在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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.