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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM