现在做的项目里,遇到了这样的情况:tableview中一个cell里嵌套了web view,想让web view根据内容自适应高度,cell根据webView自适应高度,我是自定义的cell。
我是这么解决的:
在自定义cell的webView代理方法中,让webView的高度自适应,并调用代理(有tableview的那个controller)的代理方法 webViewDidFinishLoad
SourceCell6.m
#pragma mark - UIWebView Delegate Methods -(void)webViewDidFinishLoad:(UIWebView *)webView { CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]; CGRect frame = webView.frame; frame.size.height = height+50; [webView setFrame:CGRectMake(10, 10, frame.size.width, frame.size.height)]; [self.bgView setFrame:CGRectMake(5, 5, 310,frame.size.height+10)]; [self addSubview:self.backgroundView]; [self.delegate webViewDidFinishLoad:webView]; }
在HViewController.m中,
使用变量cellRefreshCount标记cell刷新的次数,初始化为0
使用全局变量newHeight,标记重绘的cell的高度
实现SourceCell的代理方法 webViewDidFinishLoad:
#pragma mark - SourceCell6Delegate Method -(void)webViewDidFinishLoad:(UIWebView *)webView { cellRefreshCount++; //防止一直刷新 if (cellRefreshCount == 1) { //cell的高度为webView的高度 newHeight = webView.frame.size.height; //刷新第5个section,第1行 NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:4]; NSArray *paths = [NSArray arrayWithObjects:path,nil]; [self.companyTable reloadRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationNone]; } else { return; } }
这个方法不一定是最好的,但是目前为止,我就想到了这种解决方案,并是行之有效的。如果哪位同学有更好的方法,欢迎交流。