tableViewCell中添加webView,cell自适应webView高度,解决死循环的简单办法

  1. 在cell.m文件里面

这个方法是在webview请求成功的时候走的,(如果该方法不走,说明请求不成功)在此方法中获取webview的内容高度

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
        //  float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];     //此方法获取webview的内容高度,但是有时获取的不完全
        //  float height = [webView sizeThatFits:CGSizeZero].height; //此方法获取webview的高度
            float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"]floatValue]; //此方法获取webview的内容高度(建议使用)
        //设置通知或者代理来传高度
            [[NSNotificationCenter defaultCenter]postNotificationName:@"getCellHightNotification" object:nil         userInfo:@{@"height":[NSNumber numberWithFloat:height]}];
    }

该方法是在请求失败的时候走的,如果请求不成功,可以在此打印失败信息

    -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
    {
        NSLog(@"%@",error);
    }

  1. 在- (void)viewDidLoad方法里面接受通知
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setTableViewCellHight:)  name:@"getCellHightNotification" object:nil];

  1. 实现通知中的方法(在此防止死循环)
    -(void)setTableViewCellHight:(NSNotification *)info
    {
        NSDictionary * dic=info.userInfo;
        //判断通知中的参数是否与原来的值一致,防止死循环
        if (_height != [[dic objectForKey:@"height"]floatValue])
        {
            _height=[[dic objectForKey:@"height"]floatValue];
            [self.tableView reloadData];
        }
    }

posted on 2017-03-07 20:26  Littleredguy鲁  阅读(2236)  评论(0编辑  收藏  举报

导航