前言:今天有个需求,要在tableview中一个cell里嵌套了webView,想让Cell高度根据WebView高度进行自适应。
废话少说上代码:
在自定义Cell.m文件中
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
self.webView = [[UIWebView alloc]init];
//创建URL
NSURL* url = [NSURL URLWithString:@"http://172.16.50.9:8080/yi-ad-h5/index.html"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
self.webView.opaque = NO;
self.webView.userInteractionEnabled = NO;
self.webView.scrollView.bounces = NO;
self.webView.delegate = self;
self.webView.paginationBreakingMode = UIWebPaginationBreakingModePage;
self.webView.scalesPageToFit = YES;
[_webView loadRequest:request];
[self.contentView addSubview:_webView];
[_webView mas_makeConstraints:^(MASConstraintMaker *make){
make.left.mas_equalTo(self.contentView.mas_left);
make.right.mas_equalTo(self.contentView.mas_right);
make.top.mas_equalTo(self.contentView.mas_top);
make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-15);
}];
}
return self;
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 如果要获取web高度必须在网页加载完成之后获取
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];
//使用代理在ViewController中调用代理方法
if (self.delegate && [self.delegate respondsToSelector:@selector(setwebViewDidFinishLoad:)]) {
[self.delegate setwebViewDidFinishLoad:webView];
}
}
ViewController.m 文件
#pragma mark -- 获取cell的高度Delegate
- (void)setwebViewDidFinishLoad:(UIWebView *)web
{
cellRefreshCount++;
//防止一直刷新
if (cellRefreshCount == 1) {
//cell的高度为webView的高度
webHeight = web.frame.size.height;
//刷新section
NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:1];
NSArray *paths = [NSArray arrayWithObjects:path,nil];
[self.tableView reloadRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationNone];
}
else
{
return;
}
NSLog(@"cell的高度 === %ld",(long)newHeight);
}
如果有问题还请大家指出;
原文链接:http://www.xuebuyuan.com/2035051.html
网友评论