我想将一个UIWebView添加到一个单元格中。HTML数据将发生变化,当这种情况发生时,我将调用reloadData。
问题是,UIWebView的变化很好,但是我不能让UITableViewCell正确地匹配高度。我尝试过这个解决方案,但失败了。
当webview加载时:
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
CGRect frame = aWebView.frame;
int old_height = frame.size.height;
frame.size = CGSizeMake(280, 0);
aWebView.frame = frame;
float content_height = [[aWebView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
frame = aWebView.frame;
frame.size = CGSizeMake(280, content_height + 20);
aWebView.frame = frame;
NSLog(@"SIZES - %i - %i",old_height + 4,(int) frame.size.height);
if(old_height + 4 != frame.size.height){
[self.tableView reloadData];
}
}单元格返回高度:
return webview.frame.size.height + 20;在第一次加载之后,计算单元的大小不正确。很难弄清楚如何做到这一点。我需要将整个内容向下拉伸以适合一个单元格。
谢谢。
发布于 2011-05-25 18:56:25
UIWebView不是设计用来在另一个滚动条(如UITableView)中工作的;
若要调整单元格的大小,应使用UITableView.rowHeight属性或以下UITableViewDelegate方法:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
顺便说一句,对于更新表来说,UITableView reloadData通常是一个糟糕的决定。
发布于 2012-01-27 16:30:39
遇到了同样的问题,下面是我是如何解决它的。
据我所知,UIWebView不会正确计算它的高度,除非它添加了根植于窗口的superview。所以我所做的是1)创建alpha为0的WebView,然后2)将它添加到我的UIViewController的视图中,然后3)加载后将它重新设置为我的UITableViewCell的父对象,并将alpha设置为1。这是我的webViewDidFinishLoad的样子。
- (void)webViewDidFinishLoad:(UIWebView *)webView {
CGRect frame = webView.frame;
frame.size = [webView sizeThatFits:CGSizeZero];
frame.size.height += 20.0f; // additional padding to push it off the bottom edge
webView.frame = frame;
webView.delegate = nil;
UITableViewCell *cell =[_cells objectAtIndex:webView.tag];
[cell.contentView addSubview:[_loadingWebView autorelease]];
cell.contentView.frame = frame;
[cell setNeedsLayout];
webView.alpha = 1.0f;
[self.tableView beginUpdates];
NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:webView.tag]];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
// Storing the currently loading webView in case I need to clean it up
// before it finishes loading.
_loadingWebView = nil;
}在我的例子中,我没有重用我的表格视图单元格,并且每个web视图在每个部分都有一行,因此请相应地调整您的代码。
发布于 2016-04-17 12:55:43
NSString *htmlStr = Your html text;
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(kScreenWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
CGFloat htmlHight = CGRectGetHeight(rect);https://stackoverflow.com/questions/6118035
复制相似问题