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

来源:互联网 发布:精通matlab最优化计算 编辑:程序博客网 时间:2024/05/17 23:50

不管是使用代理还是使用通知传递高度的值,要改边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];// 也可以写成刷新某一固定的行
        }    }
1 0
原创粉丝点击