tableView嵌套webView

作者: 贼海鸥 | 来源:发表于2017-05-11 11:59 被阅读0次

在tableview中嵌套webView最重要的是获取webView的高度.然而,webView的高度需要加载完webView之后,才能通过代理得到webView的高度.那么,我们就需要先加载webView

    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, KScreenSize.width, 1)];
    _webView.delegate = self;
    _webView.scrollView.scrollEnabled = NO;
    //预先加载url
    NSURL *url = [NSURL URLWithString:@"http://www.51tsg.com/index.php?act=goods&m=1&goods_id=7008"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];

通过代理得到webView的高度

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //获取到webview的高度
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x,self.webView.frame.origin.y, KScreenSize.width, height);
    [self.tableView reloadData];
}

设置cell的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        return _webView.frame.size.height;
    }
    return 44;
}

最后,在cell中加载webView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    if (indexPath.row == 1) {
        [cell.contentView addSubview:_webView];
    }
    return cell;
}

demo下载地址
https://github.com/TheifSeaMew/WebHeight.git

相关文章

网友评论

    本文标题:tableView嵌套webView

    本文链接:https://www.haomeiwen.com/subject/ykcotxtx.html