我想将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;
第一次加载后,单元格的大小不正确。很难弄清楚如何做到这一点。我需要向下拉伸整个内容以适合单元格。
谢谢。
答案 0 :(得分:13)
进入同样的问题,这就是我如何解决它。
据我所知,UIWebView无法正确计算其高度,直到它添加了根植于窗口的超视图。所以我做的是1)创建一个alpha为0的WebView,然后2)将它添加到我的UIViewController的视图中,然后3)一旦加载并将alpha设置为1,将其重新显示给我的UITableViewCell。这就是我的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;
}
在我的情况下,我没有重复使用表格视图单元格,每个网页每个网页视图都有一行,因此请相应地调整代码。
答案 1 :(得分:0)
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);
答案 2 :(得分:-4)
UIWebView不适用于其他滚动条(如UITableView);
要调整单元格的大小,您应该使用UITableView.rowHeight
属性或以下UITableViewDelegate
方法:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
顺便说一句,[UITableView reloadData]通常是更新表格的错误决定。