tableViewCell中添加webView,cell自適應webView高度,解決死循環的簡單辦法

  1. 在cell.m文件裏面

這個方法是在webview請求成功的時候走的,(若是該方法不走,說明請求不成功)在此方法中獲取webview的內容高度java

- (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]}];
    }

該方法是在請求失敗的時候走的,若是請求不成功,能夠在此打印失敗信息web

    -(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];
        }
    }
相關文章
相關標籤/搜索