UITableViewCell嵌套UIWebView,根据内容自适应高度

UITableViewCell嵌套UIWebView,并且让UIWebView根据内容自适应高度。
1 获取UIWebView高度

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 如果要获取webView高度必须在网页加载完成之后获取

    // 方法一
    CGFloat height = [self.webView sizeThatFits:CGSizeZero].height;

    // 方法二
    CGFloat height = webView.scrollView.contentSize.height;

    // 方法三 (不推荐使用,当webView.scalesPageToFit = YES计算的高度不准确)
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
}

2 UIWebView加载完成后cell高度的更新,使用通知来实现。

TableViewCell.m

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
    self.height = fittingSize.height;
    self.webView.frame = CGRectMake(0, 0, fittingSize.width, fittingSize.height);

    // 用通知发送加载完成后的高度
    [[NSNotificationCenter defaultCenter] postNotificationName:@"WEBVIEW_HEIGHT" object:self userInfo:nil];
}

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 用于缓存cell高度
    self.heightDic = [[NSMutableDictionary alloc] init];

    // 注册加载完成高度的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:@"WEBVIEW_HEIGHT" object:nil];
}

- (void)noti:(NSNotification *)sender
{
    TableViewCell *cell = [sender object];

    if (![self.heightDic objectForKey:[NSString stringWithFormat:@"%ld",cell.tag]]||[[self.heightDic objectForKey:[NSString stringWithFormat:@"%ld",cell.tag]] floatValue] != cell.height)
    {
        [self.heightDic setObject:[NSNumber numberWithFloat:cell.height] forKey:[NSString stringWithFormat:@"%ld",cell.tag]];
       [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:cell.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
}

完整项目工程
https://github.com/YiQieSuiYuan/Demo/tree/master/WebView_cell

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,195评论 4 61
  • 前言:今天有个需求,要在tableview中一个cell里嵌套了webView,想让Cell高度根据WebView...
    夜冰雨阅读 4,149评论 0 3
  • 这几天小酷的朋友圈被高考的话题刷爆了,其中有一段话小酷印象很深刻: 祝高考的考生们考试顺利!四年后你们会明白,你们...
    酷听听书阅读 3,244评论 0 1
  • 这个世界上让人温暖和感动的词第一个就是“爱”。人们渴望亲人的爱、朋友的爱、恋人的爱甚至是陌生人的爱。因为爱...
    微木之末阅读 715评论 0 0
  • 吃多饲料农药地沟油养成的食肴从而形成荒诞可笑略羞耻的思想让我恶心 晴时候是雨 雨时候也是雨 暖时候是冷 冷时候也是...
    陈秋实阅读 1,436评论 0 0