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

不管是使用代理还是使用通知传递高度的值,要改边tableviewcell的高度,都需要刷新表,但是这个表刷新,>又要导致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];
        }

}

(来源)http://blog.cocoachina.com/article/14311

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值